├── .gitattributes ├── .gitignore ├── Syntax Highlighting for Code.py └── code_highlight_addon ├── __init__.py ├── code_highlight_addon.py ├── docs.txt ├── examples ├── haskell-example.png └── python-example.png ├── icons └── button-icon.png ├── lang.txt ├── pygments ├── __init__.py ├── cmdline.py ├── console.py ├── filter.py ├── filters │ └── __init__.py ├── formatter.py ├── formatters │ ├── __init__.py │ ├── _mapping.py │ ├── bbcode.py │ ├── html.py │ ├── img.py │ ├── latex.py │ ├── other.py │ ├── rtf.py │ ├── svg.py │ ├── terminal.py │ └── terminal256.py ├── lexer.py ├── lexers │ ├── __init__.py │ ├── _asybuiltins.py │ ├── _clbuiltins.py │ ├── _luabuiltins.py │ ├── _mapping.py │ ├── _phpbuiltins.py │ ├── _postgres_builtins.py │ ├── _vimbuiltins.py │ ├── agile.py │ ├── asm.py │ ├── compiled.py │ ├── dotnet.py │ ├── functional.py │ ├── hdl.py │ ├── jvm.py │ ├── math.py │ ├── other.py │ ├── parsers.py │ ├── shell.py │ ├── special.py │ ├── sql.py │ ├── templates.py │ ├── text.py │ └── web.py ├── plugin.py ├── scanner.py ├── style.py ├── styles │ ├── __init__.py │ ├── autumn.py │ ├── borland.py │ ├── bw.py │ ├── colorful.py │ ├── default.py │ ├── emacs.py │ ├── friendly.py │ ├── fruity.py │ ├── manni.py │ ├── monokai.py │ ├── murphy.py │ ├── native.py │ ├── pastie.py │ ├── perldoc.py │ ├── rrt.py │ ├── tango.py │ ├── trac.py │ ├── vim.py │ └── vs.py ├── token.py ├── unistring.py └── util.py ├── resources.py └── resources.qrc /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | tmp/ 10 | *.tmp 11 | *.bak 12 | *.swp 13 | *~.nib 14 | local.properties 15 | .classpath 16 | .settings/ 17 | .loadpath 18 | 19 | # External tool builders 20 | .externalToolBuilders/ 21 | 22 | # Locally stored "Eclipse launch configurations" 23 | *.launch 24 | 25 | # CDT-specific 26 | .cproject 27 | 28 | # PDT-specific 29 | .buildpath 30 | 31 | 32 | ################# 33 | ## Visual Studio 34 | ################# 35 | 36 | ## Ignore Visual Studio temporary files, build results, and 37 | ## files generated by popular Visual Studio add-ons. 38 | 39 | # User-specific files 40 | *.suo 41 | *.user 42 | *.sln.docstates 43 | 44 | # Build results 45 | [Dd]ebug/ 46 | [Rr]elease/ 47 | *_i.c 48 | *_p.c 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.vspscc 63 | .builds 64 | *.dotCover 65 | 66 | ## TODO: If you have NuGet Package Restore enabled, uncomment this 67 | #packages/ 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | 76 | # Visual Studio profiler 77 | *.psess 78 | *.vsp 79 | 80 | # ReSharper is a .NET coding add-in 81 | _ReSharper* 82 | 83 | # Installshield output folder 84 | [Ee]xpress 85 | 86 | # DocProject is a documentation generator add-in 87 | DocProject/buildhelp/ 88 | DocProject/Help/*.HxT 89 | DocProject/Help/*.HxC 90 | DocProject/Help/*.hhc 91 | DocProject/Help/*.hhk 92 | DocProject/Help/*.hhp 93 | DocProject/Help/Html2 94 | DocProject/Help/html 95 | 96 | # Click-Once directory 97 | publish 98 | 99 | # Others 100 | [Bb]in 101 | [Oo]bj 102 | sql 103 | TestResults 104 | *.Cache 105 | ClientBin 106 | stylecop.* 107 | ~$* 108 | *.dbmdl 109 | Generated_Code #added for RIA/Silverlight projects 110 | 111 | # Backup & report files from converting an old project file to a newer 112 | # Visual Studio version. Backup files are not needed, because we have git ;-) 113 | _UpgradeReport_Files/ 114 | Backup*/ 115 | UpgradeLog*.XML 116 | 117 | 118 | 119 | ############ 120 | ## Windows 121 | ############ 122 | 123 | # Windows image file caches 124 | Thumbs.db 125 | 126 | # Folder config file 127 | Desktop.ini 128 | 129 | 130 | ############# 131 | ## Python 132 | ############# 133 | 134 | *.py[co] 135 | 136 | # Packages 137 | *.egg 138 | *.egg-info 139 | dist 140 | build 141 | eggs 142 | parts 143 | bin 144 | var 145 | sdist 146 | develop-eggs 147 | .installed.cfg 148 | 149 | # Installer logs 150 | pip-log.txt 151 | 152 | # Unit test / coverage reports 153 | .coverage 154 | .tox 155 | 156 | #Translations 157 | *.mo 158 | 159 | #Mr Developer 160 | .mr.developer.cfg 161 | 162 | # Mac crap 163 | .DS_Store 164 | -------------------------------------------------------------------------------- /Syntax Highlighting for Code.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import code_highlight_addon.code_highlight_addon -------------------------------------------------------------------------------- /code_highlight_addon/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tmbb/SyntaxHighlight/0ccea2515ef544ed5086a6290e0719c7216a7ead/code_highlight_addon/__init__.py -------------------------------------------------------------------------------- /code_highlight_addon/code_highlight_addon.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from PyQt4.QtCore import * 4 | from PyQt4.QtGui import * 5 | 6 | import os 7 | import sys 8 | 9 | from aqt import editor, addons, mw 10 | #from aqt.utils import showInfo 11 | # For those who are wondering, 'mw' means "Main Window" 12 | from anki.utils import json 13 | from anki import hooks 14 | 15 | # import the lightning bolt icon 16 | from resources import * 17 | 18 | def debug_trace(): 19 | '''Set a tracepoint in the Python debugger that works with Qt''' 20 | from PyQt4.QtCore import pyqtRemoveInputHook 21 | from pdb import set_trace 22 | pyqtRemoveInputHook() 23 | set_trace() 24 | 25 | ############################################################### 26 | ### 27 | ### Utilities to generate buttons 28 | ### 29 | ############################################################### 30 | standardHeight = 20 31 | standardWidth = 20 32 | 33 | # This is taken from the aqt source code to 34 | def add_plugin_button_(self, 35 | ed, 36 | name, 37 | func, 38 | text="", 39 | key=None, 40 | tip=None, 41 | height=False, 42 | width=False, 43 | icon=None, 44 | check=False, 45 | native=False, 46 | canDisable=True): 47 | 48 | b = QPushButton(text) 49 | 50 | if check: 51 | b.connect(b, SIGNAL("clicked(bool)"), func) 52 | else: 53 | b.connect(b, SIGNAL("clicked()"), func) 54 | 55 | if height: 56 | b.setFixedHeight(height) 57 | if width: 58 | b.setFixedWidth(width) 59 | 60 | if not native: 61 | b.setStyle(ed.plastiqueStyle) 62 | b.setFocusPolicy(Qt.NoFocus) 63 | else: 64 | b.setAutoDefault(False) 65 | 66 | if icon: 67 | b.setIcon(QIcon(icon)) 68 | if key: 69 | b.setShortcut(QKeySequence(key)) 70 | if tip: 71 | b.setToolTip(tip) 72 | if check: 73 | b.setCheckable(True) 74 | 75 | self.addWidget(b) # this part is changed 76 | 77 | if canDisable: 78 | ed._buttons[name] = b 79 | return b 80 | 81 | ############################################################### 82 | def add_code_langs_combobox(self, func, previous_lang): 83 | combo = QComboBox() 84 | combo.addItem(previous_lang) 85 | for lang in sorted(LANGUAGES_MAP.iterkeys()): 86 | combo.addItem(lang) 87 | 88 | combo.activated[str].connect(func) 89 | self.addWidget(combo) 90 | return combo 91 | 92 | ############################################################### 93 | ### 94 | ### Configurable preferences 95 | ### 96 | ############################################################### 97 | #### Defaults conf 98 | #### - we create a new item in mw.col.conf. This syncs the 99 | #### options across machines (but not on mobile) 100 | default_conf = {'linenos': True, # show numbers by default 101 | 'centerfragments': True, # Use
when generating code fragments 102 | 'defaultlangperdeck': True, # Default to last used language per deck 103 | 'deckdefaultlang': {}, # Map to store the default language per deck 104 | 'lang': 'Python'} # default language is Python 105 | ############################################################### 106 | 107 | def sync_keys(tosync, ref): 108 | for key in [ x for x in tosync.keys() if x not in ref ]: 109 | del(tosync[key]) 110 | 111 | for key in [ x for x in ref.keys() if x not in tosync ]: 112 | tosync[key] = ref[key] 113 | 114 | def sync_config_with_default(col): 115 | if not 'syntax_highlighting_conf' in col.conf: 116 | col.conf['syntax_highlighting_conf'] = default_conf 117 | else: 118 | sync_keys(col.conf['syntax_highlighting_conf'], default_conf) 119 | 120 | # Mark collection state as modified, else config changes get lost unless 121 | # some unrelated action triggers the flush of collection data to db 122 | col.setMod() 123 | #col.flush() 124 | 125 | def get_deck_name(mw): 126 | deck_name = None 127 | try: 128 | deck_name = mw.col.decks.current()['name'] 129 | except AttributeError: 130 | # No deck opened? 131 | deck_name = None 132 | return deck_name 133 | 134 | def get_default_lang(mw): 135 | addon_conf = mw.col.conf['syntax_highlighting_conf'] 136 | lang = addon_conf['lang'] 137 | if addon_conf['defaultlangperdeck']: 138 | deck_name = get_deck_name(mw) 139 | if deck_name and deck_name in addon_conf['deckdefaultlang']: 140 | lang = addon_conf['deckdefaultlang'][deck_name] 141 | return lang 142 | 143 | def set_default_lang(mw, lang): 144 | addon_conf = mw.col.conf['syntax_highlighting_conf'] 145 | addon_conf['lang'] = lang # Always update the overall default 146 | if addon_conf['defaultlangperdeck']: 147 | deck_name = get_deck_name(mw) 148 | if deck_name: 149 | addon_conf['deckdefaultlang'][deck_name] = lang 150 | 151 | class SyntaxHighlighting_Options(QWidget): 152 | def __init__(self, mw): 153 | super(SyntaxHighlighting_Options, self).__init__() 154 | self.mw = mw 155 | self.addon_conf = None 156 | 157 | def switch_linenos(self): 158 | linenos_ = self.addon_conf['linenos'] 159 | self.addon_conf['linenos'] = not linenos_ 160 | 161 | def switch_centerfragments(self): 162 | centerfragments_ = self.addon_conf['centerfragments'] 163 | self.addon_conf['centerfragments'] = not centerfragments_ 164 | 165 | def switch_defaultlangperdeck(self): 166 | defaultlangperdeck_ = self.addon_conf['defaultlangperdeck'] 167 | self.addon_conf['defaultlangperdeck'] = not defaultlangperdeck_ 168 | 169 | def setupUi(self): 170 | # If config options have changed, sync with default config first 171 | sync_config_with_default(self.mw.col) 172 | 173 | self.addon_conf = self.mw.col.conf['syntax_highlighting_conf'] 174 | 175 | linenos_label = QLabel('Line numbers') 176 | linenos_checkbox = QCheckBox('') 177 | linenos_checkbox.setChecked(self.addon_conf['linenos']) 178 | linenos_checkbox.stateChanged.connect(self.switch_linenos) 179 | 180 | center_label = QLabel('Center code fragments') 181 | center_checkbox = QCheckBox('') 182 | center_checkbox.setChecked(self.addon_conf['centerfragments']) 183 | center_checkbox.stateChanged.connect(self.switch_centerfragments) 184 | 185 | defaultlangperdeck_label = QLabel('Default to last language used per deck') 186 | defaultlangperdeck_checkbox = QCheckBox('') 187 | defaultlangperdeck_checkbox.setChecked(self.addon_conf['defaultlangperdeck']) 188 | defaultlangperdeck_checkbox.stateChanged.connect(self.switch_defaultlangperdeck) 189 | 190 | grid = QGridLayout() 191 | grid.setSpacing(10) 192 | grid.addWidget(linenos_label, 0, 0) 193 | grid.addWidget(linenos_checkbox, 0, 1) 194 | grid.addWidget(center_label, 1, 0) 195 | grid.addWidget(center_checkbox, 1, 1) 196 | grid.addWidget(defaultlangperdeck_label, 2, 0) 197 | grid.addWidget(defaultlangperdeck_checkbox, 2, 1) 198 | 199 | self.setLayout(grid) 200 | 201 | self.setWindowTitle('Syntax Highlighting Options') 202 | self.show() 203 | 204 | 205 | mw.SyntaxHighlighting_Options = SyntaxHighlighting_Options(mw) 206 | 207 | options_action = QAction("Syntax Highlighting Options ...", mw) 208 | mw.connect(options_action, 209 | SIGNAL("triggered()"), 210 | mw.SyntaxHighlighting_Options.setupUi) 211 | mw.form.menuTools.addAction(options_action) 212 | ############################################################### 213 | 214 | ############################################################### 215 | QSplitter.add_plugin_button_ = add_plugin_button_ 216 | QSplitter.add_code_langs_combobox = add_code_langs_combobox 217 | 218 | def init_highlighter(ed, *args, **kwargs): 219 | # If config options have changed, sync with default config first 220 | sync_config_with_default(mw.col) 221 | 222 | # Get the last selected language (or the default language if the user 223 | # has never chosen any) 224 | previous_lang = get_default_lang(mw) 225 | ed.codeHighlightLangAlias = LANGUAGES_MAP[previous_lang] 226 | 227 | ### Add the buttons to the Icon Box 228 | splitter = QSplitter() 229 | splitter.add_plugin_button_(ed, 230 | "highlight_code", 231 | ed.highlight_code, 232 | key="Alt+s", 233 | height=standardHeight, 234 | width=standardWidth, 235 | text="", 236 | icon=":/icons/button-icon.png", 237 | tip=_("Paste highlighted code (Alt+s)"), 238 | check=False) 239 | splitter.add_code_langs_combobox(ed.onCodeHighlightLangSelect, previous_lang) 240 | splitter.setFrameStyle(QFrame.Plain) 241 | rect = splitter.frameRect() 242 | splitter.setFrameRect(rect.adjusted(10,0,-10,0)) 243 | ed.iconsBox.addWidget(splitter) 244 | 245 | def onCodeHighlightLangSelect(self, lang): 246 | set_default_lang(mw, lang) 247 | alias = LANGUAGES_MAP[lang] 248 | self.codeHighlightLangAlias = alias 249 | 250 | ############################################################### 251 | 252 | ############################################################### 253 | ### 254 | ### Deals with highlighting 255 | ### 256 | ############################################################### 257 | def addons_folder(): return mw.pm.addonFolder() 258 | 259 | # Tell Python where to look here for our stripped down 260 | # version of the Pygments package: 261 | try: 262 | __import__('pygments') 263 | except ImportError: 264 | sys.path.insert(0, os.path.join(addons_folder(), "code_highlight_addon")) 265 | 266 | # Choose default language from the last to be used 267 | #lang_file_path = os.path.join(addons_folder(), "code_highlight_addon", "lang.txt") 268 | 269 | from pygments import highlight 270 | from pygments.lexers import get_lexer_by_name, get_all_lexers 271 | from pygments.formatters import HtmlFormatter 272 | 273 | # This code sets a correspondence between: 274 | # The "language names": long, descriptive names we want 275 | # to show the user AND 276 | # The "language aliases": short, cryptic names for internal 277 | # use by HtmlFormatter 278 | LANGUAGES_MAP = {} 279 | for lex in get_all_lexers(): 280 | # This line uses the somewhat weird structure of the the map 281 | # returned by get_all_lexers 282 | LANGUAGES_MAP[lex[0]] = lex[1][0] 283 | 284 | ############################################################### 285 | def highlight_code(self): 286 | addon_conf = mw.col.conf['syntax_highlighting_conf'] 287 | 288 | # Do we want line numbers? linenos is either true or false according 289 | # to the user's preferences 290 | linenos = addon_conf['linenos'] 291 | 292 | centerfragments = addon_conf['centerfragments'] 293 | 294 | selected_text = self.web.selectedText() 295 | if selected_text: 296 | # Sometimes, self.web.selectedText() contains the unicode character 297 | # '\u00A0' (non-breaking space). This character messes with the 298 | # formatter for highlighted code. To correct this, we replace all 299 | # '\u00A0' characters with regular space characters 300 | code = selected_text.replace(u'\u00A0', ' ') 301 | else: 302 | clipboard = QApplication.clipboard() 303 | # Get the code from the clipboard 304 | code = clipboard.text() 305 | 306 | langAlias = self.codeHighlightLangAlias 307 | 308 | # Select the lexer for the correct language 309 | my_lexer = get_lexer_by_name(langAlias, stripall=True) 310 | # Tell pygments that we will be generating HTML without CSS. 311 | # HTML without CSS may take more space, but it's self contained. 312 | 313 | my_formatter = HtmlFormatter(linenos=linenos, noclasses=True, font_size=16) 314 | if linenos: 315 | if centerfragments: 316 | pretty_code = "".join(["
", 317 | highlight(code, my_lexer, my_formatter), 318 | "

"]) 319 | else: 320 | pretty_code = "".join([highlight(code, my_lexer, my_formatter), 321 | "
"]) 322 | # TODO: understand why this is neccessary 323 | else: 324 | if centerfragments: 325 | pretty_code = "".join(["
", 326 | highlight(code, my_lexer, my_formatter), 327 | "

"]) 328 | else: 329 | pretty_code = "".join(["
", 330 | highlight(code, my_lexer, my_formatter), 331 | "

"]) 332 | 333 | # These two lines insert a piece of HTML in the current cursor position 334 | self.web.eval("document.execCommand('inserthtml', false, %s);" 335 | % json.dumps(pretty_code)) 336 | 337 | editor.Editor.onCodeHighlightLangSelect = onCodeHighlightLangSelect 338 | editor.Editor.highlight_code = highlight_code 339 | editor.Editor.__init__ = hooks.wrap(editor.Editor.__init__, init_highlighter) 340 | 341 | -------------------------------------------------------------------------------- /code_highlight_addon/docs.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tmbb/SyntaxHighlight/0ccea2515ef544ed5086a6290e0719c7216a7ead/code_highlight_addon/docs.txt -------------------------------------------------------------------------------- /code_highlight_addon/examples/haskell-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tmbb/SyntaxHighlight/0ccea2515ef544ed5086a6290e0719c7216a7ead/code_highlight_addon/examples/haskell-example.png -------------------------------------------------------------------------------- /code_highlight_addon/examples/python-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tmbb/SyntaxHighlight/0ccea2515ef544ed5086a6290e0719c7216a7ead/code_highlight_addon/examples/python-example.png -------------------------------------------------------------------------------- /code_highlight_addon/icons/button-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tmbb/SyntaxHighlight/0ccea2515ef544ed5086a6290e0719c7216a7ead/code_highlight_addon/icons/button-icon.png -------------------------------------------------------------------------------- /code_highlight_addon/lang.txt: -------------------------------------------------------------------------------- 1 | Python -------------------------------------------------------------------------------- /code_highlight_addon/pygments/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Pygments 4 | ~~~~~~~~ 5 | 6 | Pygments is a syntax highlighting package written in Python. 7 | 8 | It is a generic syntax highlighter for general use in all kinds of software 9 | such as forum systems, wikis or other applications that need to prettify 10 | source code. Highlights are: 11 | 12 | * a wide range of common languages and markup formats is supported 13 | * special attention is paid to details, increasing quality by a fair amount 14 | * support for new languages and formats are added easily 15 | * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image 16 | formats that PIL supports, and ANSI sequences 17 | * it is usable as a command-line tool and as a library 18 | * ... and it highlights even Brainfuck! 19 | 20 | The `Pygments tip`_ is installable with ``easy_install Pygments==dev``. 21 | 22 | .. _Pygments tip: 23 | http://bitbucket.org/birkenfeld/pygments-main/get/tip.zip#egg=Pygments-dev 24 | 25 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 26 | :license: BSD, see LICENSE for details. 27 | """ 28 | 29 | __version__ = '1.4' 30 | __docformat__ = 'restructuredtext' 31 | 32 | __all__ = ['lex', 'format', 'highlight'] 33 | 34 | 35 | import sys 36 | 37 | from pygments.util import StringIO, BytesIO 38 | 39 | def lex(code, lexer): 40 | """ 41 | Lex ``code`` with ``lexer`` and return an iterable of tokens. 42 | """ 43 | try: 44 | return lexer.get_tokens(code) 45 | except TypeError, err: 46 | if isinstance(err.args[0], str) and \ 47 | 'unbound method get_tokens' in err.args[0]: 48 | raise TypeError('lex() argument must be a lexer instance, ' 49 | 'not a class') 50 | raise 51 | 52 | 53 | def format(tokens, formatter, outfile=None): 54 | """ 55 | Format a tokenlist ``tokens`` with the formatter ``formatter``. 56 | 57 | If ``outfile`` is given and a valid file object (an object 58 | with a ``write`` method), the result will be written to it, otherwise 59 | it is returned as a string. 60 | """ 61 | try: 62 | if not outfile: 63 | #print formatter, 'using', formatter.encoding 64 | realoutfile = formatter.encoding and BytesIO() or StringIO() 65 | formatter.format(tokens, realoutfile) 66 | return realoutfile.getvalue() 67 | else: 68 | formatter.format(tokens, outfile) 69 | except TypeError, err: 70 | if isinstance(err.args[0], str) and \ 71 | 'unbound method format' in err.args[0]: 72 | raise TypeError('format() argument must be a formatter instance, ' 73 | 'not a class') 74 | raise 75 | 76 | 77 | def highlight(code, lexer, formatter, outfile=None): 78 | """ 79 | Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``. 80 | 81 | If ``outfile`` is given and a valid file object (an object 82 | with a ``write`` method), the result will be written to it, otherwise 83 | it is returned as a string. 84 | """ 85 | return format(lex(code, lexer), formatter, outfile) 86 | 87 | 88 | if __name__ == '__main__': 89 | from pygments.cmdline import main 90 | sys.exit(main(sys.argv)) 91 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/console.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.console 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | Format colored console output. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | esc = "\x1b[" 13 | 14 | codes = {} 15 | codes[""] = "" 16 | codes["reset"] = esc + "39;49;00m" 17 | 18 | codes["bold"] = esc + "01m" 19 | codes["faint"] = esc + "02m" 20 | codes["standout"] = esc + "03m" 21 | codes["underline"] = esc + "04m" 22 | codes["blink"] = esc + "05m" 23 | codes["overline"] = esc + "06m" 24 | 25 | dark_colors = ["black", "darkred", "darkgreen", "brown", "darkblue", 26 | "purple", "teal", "lightgray"] 27 | light_colors = ["darkgray", "red", "green", "yellow", "blue", 28 | "fuchsia", "turquoise", "white"] 29 | 30 | x = 30 31 | for d, l in zip(dark_colors, light_colors): 32 | codes[d] = esc + "%im" % x 33 | codes[l] = esc + "%i;01m" % x 34 | x += 1 35 | 36 | del d, l, x 37 | 38 | codes["darkteal"] = codes["turquoise"] 39 | codes["darkyellow"] = codes["brown"] 40 | codes["fuscia"] = codes["fuchsia"] 41 | codes["white"] = codes["bold"] 42 | 43 | 44 | def reset_color(): 45 | return codes["reset"] 46 | 47 | 48 | def colorize(color_key, text): 49 | return codes[color_key] + text + codes["reset"] 50 | 51 | 52 | def ansiformat(attr, text): 53 | """ 54 | Format ``text`` with a color and/or some attributes:: 55 | 56 | color normal color 57 | *color* bold color 58 | _color_ underlined color 59 | +color+ blinking color 60 | """ 61 | result = [] 62 | if attr[:1] == attr[-1:] == '+': 63 | result.append(codes['blink']) 64 | attr = attr[1:-1] 65 | if attr[:1] == attr[-1:] == '*': 66 | result.append(codes['bold']) 67 | attr = attr[1:-1] 68 | if attr[:1] == attr[-1:] == '_': 69 | result.append(codes['underline']) 70 | attr = attr[1:-1] 71 | result.append(codes[attr]) 72 | result.append(text) 73 | result.append(codes['reset']) 74 | return ''.join(result) 75 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/filter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.filter 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Module that implements the default filter. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | 13 | def apply_filters(stream, filters, lexer=None): 14 | """ 15 | Use this method to apply an iterable of filters to 16 | a stream. If lexer is given it's forwarded to the 17 | filter, otherwise the filter receives `None`. 18 | """ 19 | def _apply(filter_, stream): 20 | for token in filter_.filter(lexer, stream): 21 | yield token 22 | for filter_ in filters: 23 | stream = _apply(filter_, stream) 24 | return stream 25 | 26 | 27 | def simplefilter(f): 28 | """ 29 | Decorator that converts a function into a filter:: 30 | 31 | @simplefilter 32 | def lowercase(lexer, stream, options): 33 | for ttype, value in stream: 34 | yield ttype, value.lower() 35 | """ 36 | return type(f.__name__, (FunctionFilter,), { 37 | 'function': f, 38 | '__module__': getattr(f, '__module__'), 39 | '__doc__': f.__doc__ 40 | }) 41 | 42 | 43 | class Filter(object): 44 | """ 45 | Default filter. Subclass this class or use the `simplefilter` 46 | decorator to create own filters. 47 | """ 48 | 49 | def __init__(self, **options): 50 | self.options = options 51 | 52 | def filter(self, lexer, stream): 53 | raise NotImplementedError() 54 | 55 | 56 | class FunctionFilter(Filter): 57 | """ 58 | Abstract class used by `simplefilter` to create simple 59 | function filters on the fly. The `simplefilter` decorator 60 | automatically creates subclasses of this class for 61 | functions passed to it. 62 | """ 63 | function = None 64 | 65 | def __init__(self, **options): 66 | if not hasattr(self, 'function'): 67 | raise TypeError('%r used without bound function' % 68 | self.__class__.__name__) 69 | Filter.__init__(self, **options) 70 | 71 | def filter(self, lexer, stream): 72 | # pylint: disable-msg=E1102 73 | for ttype, value in self.function(lexer, stream, self.options): 74 | yield ttype, value 75 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/filters/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.filters 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | Module containing filter lookup functions and default 7 | filters. 8 | 9 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 10 | :license: BSD, see LICENSE for details. 11 | """ 12 | 13 | import re 14 | 15 | from pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \ 16 | string_to_tokentype 17 | from pygments.filter import Filter 18 | from pygments.util import get_list_opt, get_int_opt, get_bool_opt, \ 19 | get_choice_opt, ClassNotFound, OptionError 20 | from pygments.plugin import find_plugin_filters 21 | 22 | 23 | def find_filter_class(filtername): 24 | """ 25 | Lookup a filter by name. Return None if not found. 26 | """ 27 | if filtername in FILTERS: 28 | return FILTERS[filtername] 29 | for name, cls in find_plugin_filters(): 30 | if name == filtername: 31 | return cls 32 | return None 33 | 34 | 35 | def get_filter_by_name(filtername, **options): 36 | """ 37 | Return an instantiated filter. Options are passed to the filter 38 | initializer if wanted. Raise a ClassNotFound if not found. 39 | """ 40 | cls = find_filter_class(filtername) 41 | if cls: 42 | return cls(**options) 43 | else: 44 | raise ClassNotFound('filter %r not found' % filtername) 45 | 46 | 47 | def get_all_filters(): 48 | """ 49 | Return a generator of all filter names. 50 | """ 51 | for name in FILTERS: 52 | yield name 53 | for name, _ in find_plugin_filters(): 54 | yield name 55 | 56 | 57 | def _replace_special(ttype, value, regex, specialttype, 58 | replacefunc=lambda x: x): 59 | last = 0 60 | for match in regex.finditer(value): 61 | start, end = match.start(), match.end() 62 | if start != last: 63 | yield ttype, value[last:start] 64 | yield specialttype, replacefunc(value[start:end]) 65 | last = end 66 | if last != len(value): 67 | yield ttype, value[last:] 68 | 69 | 70 | class CodeTagFilter(Filter): 71 | """ 72 | Highlight special code tags in comments and docstrings. 73 | 74 | Options accepted: 75 | 76 | `codetags` : list of strings 77 | A list of strings that are flagged as code tags. The default is to 78 | highlight ``XXX``, ``TODO``, ``BUG`` and ``NOTE``. 79 | """ 80 | 81 | def __init__(self, **options): 82 | Filter.__init__(self, **options) 83 | tags = get_list_opt(options, 'codetags', 84 | ['XXX', 'TODO', 'BUG', 'NOTE']) 85 | self.tag_re = re.compile(r'\b(%s)\b' % '|'.join([ 86 | re.escape(tag) for tag in tags if tag 87 | ])) 88 | 89 | def filter(self, lexer, stream): 90 | regex = self.tag_re 91 | for ttype, value in stream: 92 | if ttype in String.Doc or \ 93 | ttype in Comment and \ 94 | ttype not in Comment.Preproc: 95 | for sttype, svalue in _replace_special(ttype, value, regex, 96 | Comment.Special): 97 | yield sttype, svalue 98 | else: 99 | yield ttype, value 100 | 101 | 102 | class KeywordCaseFilter(Filter): 103 | """ 104 | Convert keywords to lowercase or uppercase or capitalize them, which 105 | means first letter uppercase, rest lowercase. 106 | 107 | This can be useful e.g. if you highlight Pascal code and want to adapt the 108 | code to your styleguide. 109 | 110 | Options accepted: 111 | 112 | `case` : string 113 | The casing to convert keywords to. Must be one of ``'lower'``, 114 | ``'upper'`` or ``'capitalize'``. The default is ``'lower'``. 115 | """ 116 | 117 | def __init__(self, **options): 118 | Filter.__init__(self, **options) 119 | case = get_choice_opt(options, 'case', ['lower', 'upper', 'capitalize'], 'lower') 120 | self.convert = getattr(unicode, case) 121 | 122 | def filter(self, lexer, stream): 123 | for ttype, value in stream: 124 | if ttype in Keyword: 125 | yield ttype, self.convert(value) 126 | else: 127 | yield ttype, value 128 | 129 | 130 | class NameHighlightFilter(Filter): 131 | """ 132 | Highlight a normal Name token with a different token type. 133 | 134 | Example:: 135 | 136 | filter = NameHighlightFilter( 137 | names=['foo', 'bar', 'baz'], 138 | tokentype=Name.Function, 139 | ) 140 | 141 | This would highlight the names "foo", "bar" and "baz" 142 | as functions. `Name.Function` is the default token type. 143 | 144 | Options accepted: 145 | 146 | `names` : list of strings 147 | A list of names that should be given the different token type. 148 | There is no default. 149 | `tokentype` : TokenType or string 150 | A token type or a string containing a token type name that is 151 | used for highlighting the strings in `names`. The default is 152 | `Name.Function`. 153 | """ 154 | 155 | def __init__(self, **options): 156 | Filter.__init__(self, **options) 157 | self.names = set(get_list_opt(options, 'names', [])) 158 | tokentype = options.get('tokentype') 159 | if tokentype: 160 | self.tokentype = string_to_tokentype(tokentype) 161 | else: 162 | self.tokentype = Name.Function 163 | 164 | def filter(self, lexer, stream): 165 | for ttype, value in stream: 166 | if ttype is Name and value in self.names: 167 | yield self.tokentype, value 168 | else: 169 | yield ttype, value 170 | 171 | 172 | class ErrorToken(Exception): 173 | pass 174 | 175 | class RaiseOnErrorTokenFilter(Filter): 176 | """ 177 | Raise an exception when the lexer generates an error token. 178 | 179 | Options accepted: 180 | 181 | `excclass` : Exception class 182 | The exception class to raise. 183 | The default is `pygments.filters.ErrorToken`. 184 | 185 | *New in Pygments 0.8.* 186 | """ 187 | 188 | def __init__(self, **options): 189 | Filter.__init__(self, **options) 190 | self.exception = options.get('excclass', ErrorToken) 191 | try: 192 | # issubclass() will raise TypeError if first argument is not a class 193 | if not issubclass(self.exception, Exception): 194 | raise TypeError 195 | except TypeError: 196 | raise OptionError('excclass option is not an exception class') 197 | 198 | def filter(self, lexer, stream): 199 | for ttype, value in stream: 200 | if ttype is Error: 201 | raise self.exception(value) 202 | yield ttype, value 203 | 204 | 205 | class VisibleWhitespaceFilter(Filter): 206 | """ 207 | Convert tabs, newlines and/or spaces to visible characters. 208 | 209 | Options accepted: 210 | 211 | `spaces` : string or bool 212 | If this is a one-character string, spaces will be replaces by this string. 213 | If it is another true value, spaces will be replaced by ``·`` (unicode 214 | MIDDLE DOT). If it is a false value, spaces will not be replaced. The 215 | default is ``False``. 216 | `tabs` : string or bool 217 | The same as for `spaces`, but the default replacement character is ``»`` 218 | (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value 219 | is ``False``. Note: this will not work if the `tabsize` option for the 220 | lexer is nonzero, as tabs will already have been expanded then. 221 | `tabsize` : int 222 | If tabs are to be replaced by this filter (see the `tabs` option), this 223 | is the total number of characters that a tab should be expanded to. 224 | The default is ``8``. 225 | `newlines` : string or bool 226 | The same as for `spaces`, but the default replacement character is ``¶`` 227 | (unicode PILCROW SIGN). The default value is ``False``. 228 | `wstokentype` : bool 229 | If true, give whitespace the special `Whitespace` token type. This allows 230 | styling the visible whitespace differently (e.g. greyed out), but it can 231 | disrupt background colors. The default is ``True``. 232 | 233 | *New in Pygments 0.8.* 234 | """ 235 | 236 | def __init__(self, **options): 237 | Filter.__init__(self, **options) 238 | for name, default in {'spaces': u'·', 'tabs': u'»', 'newlines': u'¶'}.items(): 239 | opt = options.get(name, False) 240 | if isinstance(opt, basestring) and len(opt) == 1: 241 | setattr(self, name, opt) 242 | else: 243 | setattr(self, name, (opt and default or '')) 244 | tabsize = get_int_opt(options, 'tabsize', 8) 245 | if self.tabs: 246 | self.tabs += ' '*(tabsize-1) 247 | if self.newlines: 248 | self.newlines += '\n' 249 | self.wstt = get_bool_opt(options, 'wstokentype', True) 250 | 251 | def filter(self, lexer, stream): 252 | if self.wstt: 253 | spaces = self.spaces or ' ' 254 | tabs = self.tabs or '\t' 255 | newlines = self.newlines or '\n' 256 | regex = re.compile(r'\s') 257 | def replacefunc(wschar): 258 | if wschar == ' ': 259 | return spaces 260 | elif wschar == '\t': 261 | return tabs 262 | elif wschar == '\n': 263 | return newlines 264 | return wschar 265 | 266 | for ttype, value in stream: 267 | for sttype, svalue in _replace_special(ttype, value, regex, 268 | Whitespace, replacefunc): 269 | yield sttype, svalue 270 | else: 271 | spaces, tabs, newlines = self.spaces, self.tabs, self.newlines 272 | # simpler processing 273 | for ttype, value in stream: 274 | if spaces: 275 | value = value.replace(' ', spaces) 276 | if tabs: 277 | value = value.replace('\t', tabs) 278 | if newlines: 279 | value = value.replace('\n', newlines) 280 | yield ttype, value 281 | 282 | 283 | class GobbleFilter(Filter): 284 | """ 285 | Gobbles source code lines (eats initial characters). 286 | 287 | This filter drops the first ``n`` characters off every line of code. This 288 | may be useful when the source code fed to the lexer is indented by a fixed 289 | amount of space that isn't desired in the output. 290 | 291 | Options accepted: 292 | 293 | `n` : int 294 | The number of characters to gobble. 295 | 296 | *New in Pygments 1.2.* 297 | """ 298 | def __init__(self, **options): 299 | Filter.__init__(self, **options) 300 | self.n = get_int_opt(options, 'n', 0) 301 | 302 | def gobble(self, value, left): 303 | if left < len(value): 304 | return value[left:], 0 305 | else: 306 | return '', left - len(value) 307 | 308 | def filter(self, lexer, stream): 309 | n = self.n 310 | left = n # How many characters left to gobble. 311 | for ttype, value in stream: 312 | # Remove ``left`` tokens from first line, ``n`` from all others. 313 | parts = value.split('\n') 314 | (parts[0], left) = self.gobble(parts[0], left) 315 | for i in range(1, len(parts)): 316 | (parts[i], left) = self.gobble(parts[i], n) 317 | value = '\n'.join(parts) 318 | 319 | if value != '': 320 | yield ttype, value 321 | 322 | 323 | class TokenMergeFilter(Filter): 324 | """ 325 | Merges consecutive tokens with the same token type in the output stream of a 326 | lexer. 327 | 328 | *New in Pygments 1.2.* 329 | """ 330 | def __init__(self, **options): 331 | Filter.__init__(self, **options) 332 | 333 | def filter(self, lexer, stream): 334 | output = [] 335 | current_type = None 336 | current_value = None 337 | for ttype, value in stream: 338 | if ttype is current_type: 339 | current_value += value 340 | else: 341 | if current_type is not None: 342 | yield current_type, current_value 343 | current_type = ttype 344 | current_value = value 345 | if current_type is not None: 346 | yield current_type, current_value 347 | 348 | 349 | FILTERS = { 350 | 'codetagify': CodeTagFilter, 351 | 'keywordcase': KeywordCaseFilter, 352 | 'highlight': NameHighlightFilter, 353 | 'raiseonerror': RaiseOnErrorTokenFilter, 354 | 'whitespace': VisibleWhitespaceFilter, 355 | 'gobble': GobbleFilter, 356 | 'tokenmerge': TokenMergeFilter, 357 | } 358 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatter 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Base formatter class. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | import codecs 13 | 14 | from pygments.util import get_bool_opt 15 | from pygments.styles import get_style_by_name 16 | 17 | __all__ = ['Formatter'] 18 | 19 | 20 | def _lookup_style(style): 21 | if isinstance(style, basestring): 22 | return get_style_by_name(style) 23 | return style 24 | 25 | 26 | class Formatter(object): 27 | """ 28 | Converts a token stream to text. 29 | 30 | Options accepted: 31 | 32 | ``style`` 33 | The style to use, can be a string or a Style subclass 34 | (default: "default"). Not used by e.g. the 35 | TerminalFormatter. 36 | ``full`` 37 | Tells the formatter to output a "full" document, i.e. 38 | a complete self-contained document. This doesn't have 39 | any effect for some formatters (default: false). 40 | ``title`` 41 | If ``full`` is true, the title that should be used to 42 | caption the document (default: ''). 43 | ``encoding`` 44 | If given, must be an encoding name. This will be used to 45 | convert the Unicode token strings to byte strings in the 46 | output. If it is "" or None, Unicode strings will be written 47 | to the output file, which most file-like objects do not 48 | support (default: None). 49 | ``outencoding`` 50 | Overrides ``encoding`` if given. 51 | """ 52 | 53 | #: Name of the formatter 54 | name = None 55 | 56 | #: Shortcuts for the formatter 57 | aliases = [] 58 | 59 | #: fn match rules 60 | filenames = [] 61 | 62 | #: If True, this formatter outputs Unicode strings when no encoding 63 | #: option is given. 64 | unicodeoutput = True 65 | 66 | def __init__(self, **options): 67 | self.style = _lookup_style(options.get('style', 'default')) 68 | self.full = get_bool_opt(options, 'full', False) 69 | self.title = options.get('title', '') 70 | self.encoding = options.get('encoding', None) or None 71 | self.encoding = options.get('outencoding', None) or self.encoding 72 | self.options = options 73 | 74 | def get_style_defs(self, arg=''): 75 | """ 76 | Return the style definitions for the current style as a string. 77 | 78 | ``arg`` is an additional argument whose meaning depends on the 79 | formatter used. Note that ``arg`` can also be a list or tuple 80 | for some formatters like the html formatter. 81 | """ 82 | return '' 83 | 84 | def format(self, tokensource, outfile): 85 | """ 86 | Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` 87 | tuples and write it into ``outfile``. 88 | """ 89 | if self.encoding: 90 | # wrap the outfile in a StreamWriter 91 | outfile = codecs.lookup(self.encoding)[3](outfile) 92 | return self.format_unencoded(tokensource, outfile) 93 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters 4 | ~~~~~~~~~~~~~~~~~~~ 5 | 6 | Pygments formatters. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | import os.path 12 | import fnmatch 13 | 14 | from pygments.formatters._mapping import FORMATTERS 15 | from pygments.plugin import find_plugin_formatters 16 | from pygments.util import ClassNotFound 17 | 18 | ns = globals() 19 | for fcls in FORMATTERS: 20 | ns[fcls.__name__] = fcls 21 | del fcls 22 | 23 | __all__ = ['get_formatter_by_name', 'get_formatter_for_filename', 24 | 'get_all_formatters'] + [cls.__name__ for cls in FORMATTERS] 25 | 26 | 27 | _formatter_alias_cache = {} 28 | _formatter_filename_cache = [] 29 | 30 | def _init_formatter_cache(): 31 | if _formatter_alias_cache: 32 | return 33 | for cls in get_all_formatters(): 34 | for alias in cls.aliases: 35 | _formatter_alias_cache[alias] = cls 36 | for fn in cls.filenames: 37 | _formatter_filename_cache.append((fn, cls)) 38 | 39 | 40 | def find_formatter_class(name): 41 | _init_formatter_cache() 42 | cls = _formatter_alias_cache.get(name, None) 43 | return cls 44 | 45 | 46 | def get_formatter_by_name(name, **options): 47 | _init_formatter_cache() 48 | cls = _formatter_alias_cache.get(name, None) 49 | if not cls: 50 | raise ClassNotFound("No formatter found for name %r" % name) 51 | return cls(**options) 52 | 53 | 54 | def get_formatter_for_filename(fn, **options): 55 | _init_formatter_cache() 56 | fn = os.path.basename(fn) 57 | for pattern, cls in _formatter_filename_cache: 58 | if fnmatch.fnmatch(fn, pattern): 59 | return cls(**options) 60 | raise ClassNotFound("No formatter found for file name %r" % fn) 61 | 62 | 63 | def get_all_formatters(): 64 | """Return a generator for all formatters.""" 65 | for formatter in FORMATTERS: 66 | yield formatter 67 | for _, formatter in find_plugin_formatters(): 68 | yield formatter 69 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/_mapping.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters._mapping 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Formatter mapping defintions. This file is generated by itself. Everytime 7 | you change something on a builtin formatter defintion, run this script from 8 | the formatters folder to update it. 9 | 10 | Do not alter the FORMATTERS dictionary by hand. 11 | 12 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 13 | :license: BSD, see LICENSE for details. 14 | """ 15 | 16 | from pygments.util import docstring_headline 17 | 18 | # start 19 | from pygments.formatters.bbcode import BBCodeFormatter 20 | from pygments.formatters.html import HtmlFormatter 21 | ############################################################## 22 | # I will not be generating images, and including these 23 | # classes would require more modules not included in Anki. 24 | ############################################################## 25 | #from pygments.formatters.img import BmpImageFormatter 26 | #from pygments.formatters.img import GifImageFormatter 27 | #from pygments.formatters.img import ImageFormatter 28 | #from pygments.formatters.img import JpgImageFormatter 29 | ############################################################## 30 | from pygments.formatters.latex import LatexFormatter 31 | from pygments.formatters.other import NullFormatter 32 | from pygments.formatters.other import RawTokenFormatter 33 | from pygments.formatters.rtf import RtfFormatter 34 | from pygments.formatters.svg import SvgFormatter 35 | from pygments.formatters.terminal import TerminalFormatter 36 | from pygments.formatters.terminal256 import Terminal256Formatter 37 | 38 | FORMATTERS = { 39 | BBCodeFormatter: ('BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'), 40 | # Lines commented out for the same reason as before 41 | #BmpImageFormatter: ('img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), 42 | #GifImageFormatter: ('img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), 43 | HtmlFormatter: ('HTML', ('html',), ('*.html', '*.htm'), "Format tokens as HTML 4 ```` tags within a ``
`` tag, wrapped in a ``
`` tag. The ``
``'s CSS class can be set by the `cssclass` option."), 44 | #ImageFormatter: ('img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), 45 | #JpgImageFormatter: ('img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'), 46 | LatexFormatter: ('LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'), 47 | NullFormatter: ('Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'), 48 | RawTokenFormatter: ('Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'), 49 | RtfFormatter: ('RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft\xc2\xae Word\xc2\xae documents.'), 50 | SvgFormatter: ('SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a ```` element with explicit ``x`` and ``y`` coordinates containing ```` elements with the individual token styles.'), 51 | Terminal256Formatter: ('Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'), 52 | TerminalFormatter: ('Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.') 53 | } 54 | 55 | if __name__ == '__main__': 56 | import sys 57 | import os 58 | 59 | # lookup formatters 60 | found_formatters = [] 61 | imports = [] 62 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) 63 | for filename in os.listdir('.'): 64 | if filename.endswith('.py') and not filename.startswith('_'): 65 | module_name = 'pygments.formatters.%s' % filename[:-3] 66 | print module_name 67 | module = __import__(module_name, None, None, ['']) 68 | for formatter_name in module.__all__: 69 | imports.append((module_name, formatter_name)) 70 | formatter = getattr(module, formatter_name) 71 | found_formatters.append( 72 | '%s: %r' % (formatter_name, 73 | (formatter.name, 74 | tuple(formatter.aliases), 75 | tuple(formatter.filenames), 76 | docstring_headline(formatter)))) 77 | # sort them, that should make the diff files for svn smaller 78 | found_formatters.sort() 79 | imports.sort() 80 | 81 | # extract useful sourcecode from this file 82 | f = open(__file__) 83 | try: 84 | content = f.read() 85 | finally: 86 | f.close() 87 | header = content[:content.find('# start')] 88 | footer = content[content.find("if __name__ == '__main__':"):] 89 | 90 | # write new file 91 | f = open(__file__, 'w') 92 | f.write(header) 93 | f.write('# start\n') 94 | f.write('\n'.join(['from %s import %s' % imp for imp in imports])) 95 | f.write('\n\n') 96 | f.write('FORMATTERS = {\n %s\n}\n\n' % ',\n '.join(found_formatters)) 97 | f.write(footer) 98 | f.close() 99 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/bbcode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters.bbcode 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | BBcode formatter. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | 13 | from pygments.formatter import Formatter 14 | from pygments.util import get_bool_opt 15 | 16 | __all__ = ['BBCodeFormatter'] 17 | 18 | 19 | class BBCodeFormatter(Formatter): 20 | """ 21 | Format tokens with BBcodes. These formatting codes are used by many 22 | bulletin boards, so you can highlight your sourcecode with pygments before 23 | posting it there. 24 | 25 | This formatter has no support for background colors and borders, as there 26 | are no common BBcode tags for that. 27 | 28 | Some board systems (e.g. phpBB) don't support colors in their [code] tag, 29 | so you can't use the highlighting together with that tag. 30 | Text in a [code] tag usually is shown with a monospace font (which this 31 | formatter can do with the ``monofont`` option) and no spaces (which you 32 | need for indentation) are removed. 33 | 34 | Additional options accepted: 35 | 36 | `style` 37 | The style to use, can be a string or a Style subclass (default: 38 | ``'default'``). 39 | 40 | `codetag` 41 | If set to true, put the output into ``[code]`` tags (default: 42 | ``false``) 43 | 44 | `monofont` 45 | If set to true, add a tag to show the code with a monospace font 46 | (default: ``false``). 47 | """ 48 | name = 'BBCode' 49 | aliases = ['bbcode', 'bb'] 50 | filenames = [] 51 | 52 | def __init__(self, **options): 53 | Formatter.__init__(self, **options) 54 | self._code = get_bool_opt(options, 'codetag', False) 55 | self._mono = get_bool_opt(options, 'monofont', False) 56 | 57 | self.styles = {} 58 | self._make_styles() 59 | 60 | def _make_styles(self): 61 | for ttype, ndef in self.style: 62 | start = end = '' 63 | if ndef['color']: 64 | start += '[color=#%s]' % ndef['color'] 65 | end = '[/color]' + end 66 | if ndef['bold']: 67 | start += '[b]' 68 | end = '[/b]' + end 69 | if ndef['italic']: 70 | start += '[i]' 71 | end = '[/i]' + end 72 | if ndef['underline']: 73 | start += '[u]' 74 | end = '[/u]' + end 75 | # there are no common BBcodes for background-color and border 76 | 77 | self.styles[ttype] = start, end 78 | 79 | def format_unencoded(self, tokensource, outfile): 80 | if self._code: 81 | outfile.write('[code]') 82 | if self._mono: 83 | outfile.write('[font=monospace]') 84 | 85 | lastval = '' 86 | lasttype = None 87 | 88 | for ttype, value in tokensource: 89 | while ttype not in self.styles: 90 | ttype = ttype.parent 91 | if ttype == lasttype: 92 | lastval += value 93 | else: 94 | if lastval: 95 | start, end = self.styles[lasttype] 96 | outfile.write(''.join((start, lastval, end))) 97 | lastval = value 98 | lasttype = ttype 99 | 100 | if lastval: 101 | start, end = self.styles[lasttype] 102 | outfile.write(''.join((start, lastval, end))) 103 | 104 | if self._mono: 105 | outfile.write('[/font]') 106 | if self._code: 107 | outfile.write('[/code]') 108 | if self._code or self._mono: 109 | outfile.write('\n') 110 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/img.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters.img 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Formatter for Pixmap output. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/other.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters.other 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Other formatters: NullFormatter, RawTokenFormatter. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.formatter import Formatter 13 | from pygments.util import OptionError, get_choice_opt, b 14 | from pygments.token import Token 15 | from pygments.console import colorize 16 | 17 | __all__ = ['NullFormatter', 'RawTokenFormatter'] 18 | 19 | 20 | class NullFormatter(Formatter): 21 | """ 22 | Output the text unchanged without any formatting. 23 | """ 24 | name = 'Text only' 25 | aliases = ['text', 'null'] 26 | filenames = ['*.txt'] 27 | 28 | def format(self, tokensource, outfile): 29 | enc = self.encoding 30 | for ttype, value in tokensource: 31 | if enc: 32 | outfile.write(value.encode(enc)) 33 | else: 34 | outfile.write(value) 35 | 36 | 37 | class RawTokenFormatter(Formatter): 38 | r""" 39 | Format tokens as a raw representation for storing token streams. 40 | 41 | The format is ``tokentyperepr(tokenstring)\n``. The output can later 42 | be converted to a token stream with the `RawTokenLexer`, described in the 43 | `lexer list `_. 44 | 45 | Only two options are accepted: 46 | 47 | `compress` 48 | If set to ``'gz'`` or ``'bz2'``, compress the output with the given 49 | compression algorithm after encoding (default: ``''``). 50 | `error_color` 51 | If set to a color name, highlight error tokens using that color. If 52 | set but with no value, defaults to ``'red'``. 53 | *New in Pygments 0.11.* 54 | 55 | """ 56 | name = 'Raw tokens' 57 | aliases = ['raw', 'tokens'] 58 | filenames = ['*.raw'] 59 | 60 | unicodeoutput = False 61 | 62 | def __init__(self, **options): 63 | Formatter.__init__(self, **options) 64 | if self.encoding: 65 | raise OptionError('the raw formatter does not support the ' 66 | 'encoding option') 67 | self.encoding = 'ascii' # let pygments.format() do the right thing 68 | self.compress = get_choice_opt(options, 'compress', 69 | ['', 'none', 'gz', 'bz2'], '') 70 | self.error_color = options.get('error_color', None) 71 | if self.error_color is True: 72 | self.error_color = 'red' 73 | if self.error_color is not None: 74 | try: 75 | colorize(self.error_color, '') 76 | except KeyError: 77 | raise ValueError("Invalid color %r specified" % 78 | self.error_color) 79 | 80 | def format(self, tokensource, outfile): 81 | try: 82 | outfile.write(b('')) 83 | except TypeError: 84 | raise TypeError('The raw tokens formatter needs a binary ' 85 | 'output file') 86 | if self.compress == 'gz': 87 | import gzip 88 | outfile = gzip.GzipFile('', 'wb', 9, outfile) 89 | def write(text): 90 | outfile.write(text.encode()) 91 | flush = outfile.flush 92 | elif self.compress == 'bz2': 93 | import bz2 94 | compressor = bz2.BZ2Compressor(9) 95 | def write(text): 96 | outfile.write(compressor.compress(text.encode())) 97 | def flush(): 98 | outfile.write(compressor.flush()) 99 | outfile.flush() 100 | else: 101 | def write(text): 102 | outfile.write(text.encode()) 103 | flush = outfile.flush 104 | 105 | lasttype = None 106 | lastval = u'' 107 | if self.error_color: 108 | for ttype, value in tokensource: 109 | line = "%s\t%r\n" % (ttype, value) 110 | if ttype is Token.Error: 111 | write(colorize(self.error_color, line)) 112 | else: 113 | write(line) 114 | else: 115 | for ttype, value in tokensource: 116 | write("%s\t%r\n" % (ttype, value)) 117 | flush() 118 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/rtf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters.rtf 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A formatter that generates RTF files. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.formatter import Formatter 13 | 14 | 15 | __all__ = ['RtfFormatter'] 16 | 17 | 18 | class RtfFormatter(Formatter): 19 | """ 20 | Format tokens as RTF markup. This formatter automatically outputs full RTF 21 | documents with color information and other useful stuff. Perfect for Copy and 22 | Paste into Microsoft® Word® documents. 23 | 24 | *New in Pygments 0.6.* 25 | 26 | Additional options accepted: 27 | 28 | `style` 29 | The style to use, can be a string or a Style subclass (default: 30 | ``'default'``). 31 | 32 | `fontface` 33 | The used font famliy, for example ``Bitstream Vera Sans``. Defaults to 34 | some generic font which is supposed to have fixed width. 35 | """ 36 | name = 'RTF' 37 | aliases = ['rtf'] 38 | filenames = ['*.rtf'] 39 | 40 | unicodeoutput = False 41 | 42 | def __init__(self, **options): 43 | """ 44 | Additional options accepted: 45 | 46 | ``fontface`` 47 | Name of the font used. Could for example be ``'Courier New'`` 48 | to further specify the default which is ``'\fmodern'``. The RTF 49 | specification claims that ``\fmodern`` are "Fixed-pitch serif 50 | and sans serif fonts". Hope every RTF implementation thinks 51 | the same about modern... 52 | """ 53 | Formatter.__init__(self, **options) 54 | self.fontface = options.get('fontface') or '' 55 | 56 | def _escape(self, text): 57 | return text.replace('\\', '\\\\') \ 58 | .replace('{', '\\{') \ 59 | .replace('}', '\\}') 60 | 61 | def _escape_text(self, text): 62 | # empty strings, should give a small performance improvment 63 | if not text: 64 | return '' 65 | 66 | # escape text 67 | text = self._escape(text) 68 | if self.encoding in ('utf-8', 'utf-16', 'utf-32'): 69 | encoding = 'iso-8859-15' 70 | else: 71 | encoding = self.encoding or 'iso-8859-15' 72 | 73 | buf = [] 74 | for c in text: 75 | if ord(c) > 128: 76 | ansic = c.encode(encoding, 'ignore') or '?' 77 | if ord(ansic) > 128: 78 | ansic = '\\\'%x' % ord(ansic) 79 | else: 80 | ansic = c 81 | buf.append(r'\ud{\u%d%s}' % (ord(c), ansic)) 82 | else: 83 | buf.append(str(c)) 84 | 85 | return ''.join(buf).replace('\n', '\\par\n') 86 | 87 | def format_unencoded(self, tokensource, outfile): 88 | # rtf 1.8 header 89 | outfile.write(r'{\rtf1\ansi\deff0' 90 | r'{\fonttbl{\f0\fmodern\fprq1\fcharset0%s;}}' 91 | r'{\colortbl;' % (self.fontface and 92 | ' ' + self._escape(self.fontface) or 93 | '')) 94 | 95 | # convert colors and save them in a mapping to access them later. 96 | color_mapping = {} 97 | offset = 1 98 | for _, style in self.style: 99 | for color in style['color'], style['bgcolor'], style['border']: 100 | if color and color not in color_mapping: 101 | color_mapping[color] = offset 102 | outfile.write(r'\red%d\green%d\blue%d;' % ( 103 | int(color[0:2], 16), 104 | int(color[2:4], 16), 105 | int(color[4:6], 16) 106 | )) 107 | offset += 1 108 | outfile.write(r'}\f0') 109 | 110 | # highlight stream 111 | for ttype, value in tokensource: 112 | while not self.style.styles_token(ttype) and ttype.parent: 113 | ttype = ttype.parent 114 | style = self.style.style_for_token(ttype) 115 | buf = [] 116 | if style['bgcolor']: 117 | buf.append(r'\cb%d' % color_mapping[style['bgcolor']]) 118 | if style['color']: 119 | buf.append(r'\cf%d' % color_mapping[style['color']]) 120 | if style['bold']: 121 | buf.append(r'\b') 122 | if style['italic']: 123 | buf.append(r'\i') 124 | if style['underline']: 125 | buf.append(r'\ul') 126 | if style['border']: 127 | buf.append(r'\chbrdr\chcfpat%d' % 128 | color_mapping[style['border']]) 129 | start = ''.join(buf) 130 | if start: 131 | outfile.write('{%s ' % start) 132 | outfile.write(self._escape_text(value)) 133 | if start: 134 | outfile.write('}') 135 | 136 | outfile.write('}') 137 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/svg.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters.svg 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Formatter for SVG output. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.formatter import Formatter 13 | from pygments.util import get_bool_opt, get_int_opt 14 | 15 | __all__ = ['SvgFormatter'] 16 | 17 | 18 | def escape_html(text): 19 | """Escape &, <, > as well as single and double quotes for HTML.""" 20 | return text.replace('&', '&'). \ 21 | replace('<', '<'). \ 22 | replace('>', '>'). \ 23 | replace('"', '"'). \ 24 | replace("'", ''') 25 | 26 | 27 | class2style = {} 28 | 29 | class SvgFormatter(Formatter): 30 | """ 31 | Format tokens as an SVG graphics file. This formatter is still experimental. 32 | Each line of code is a ```` element with explicit ``x`` and ``y`` 33 | coordinates containing ```` elements with the individual token styles. 34 | 35 | By default, this formatter outputs a full SVG document including doctype 36 | declaration and the ```` root element. 37 | 38 | *New in Pygments 0.9.* 39 | 40 | Additional options accepted: 41 | 42 | `nowrap` 43 | Don't wrap the SVG ```` elements in ```` elements and 44 | don't add a XML declaration and a doctype. If true, the `fontfamily` 45 | and `fontsize` options are ignored. Defaults to ``False``. 46 | 47 | `fontfamily` 48 | The value to give the wrapping ```` element's ``font-family`` 49 | attribute, defaults to ``"monospace"``. 50 | 51 | `fontsize` 52 | The value to give the wrapping ```` element's ``font-size`` 53 | attribute, defaults to ``"14px"``. 54 | 55 | `xoffset` 56 | Starting offset in X direction, defaults to ``0``. 57 | 58 | `yoffset` 59 | Starting offset in Y direction, defaults to the font size if it is given 60 | in pixels, or ``20`` else. (This is necessary since text coordinates 61 | refer to the text baseline, not the top edge.) 62 | 63 | `ystep` 64 | Offset to add to the Y coordinate for each subsequent line. This should 65 | roughly be the text size plus 5. It defaults to that value if the text 66 | size is given in pixels, or ``25`` else. 67 | 68 | `spacehack` 69 | Convert spaces in the source to `` ``, which are non-breaking 70 | spaces. SVG provides the ``xml:space`` attribute to control how 71 | whitespace inside tags is handled, in theory, the ``preserve`` value 72 | could be used to keep all whitespace as-is. However, many current SVG 73 | viewers don't obey that rule, so this option is provided as a workaround 74 | and defaults to ``True``. 75 | """ 76 | name = 'SVG' 77 | aliases = ['svg'] 78 | filenames = ['*.svg'] 79 | 80 | def __init__(self, **options): 81 | # XXX outencoding 82 | Formatter.__init__(self, **options) 83 | self.nowrap = get_bool_opt(options, 'nowrap', False) 84 | self.fontfamily = options.get('fontfamily', 'monospace') 85 | self.fontsize = options.get('fontsize', '14px') 86 | self.xoffset = get_int_opt(options, 'xoffset', 0) 87 | fs = self.fontsize.strip() 88 | if fs.endswith('px'): fs = fs[:-2].strip() 89 | try: 90 | int_fs = int(fs) 91 | except: 92 | int_fs = 20 93 | self.yoffset = get_int_opt(options, 'yoffset', int_fs) 94 | self.ystep = get_int_opt(options, 'ystep', int_fs + 5) 95 | self.spacehack = get_bool_opt(options, 'spacehack', True) 96 | self._stylecache = {} 97 | 98 | def format_unencoded(self, tokensource, outfile): 99 | """ 100 | Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` 101 | tuples and write it into ``outfile``. 102 | 103 | For our implementation we put all lines in their own 'line group'. 104 | """ 105 | x = self.xoffset 106 | y = self.yoffset 107 | if not self.nowrap: 108 | if self.encoding: 109 | outfile.write('\n' % 110 | self.encoding) 111 | else: 112 | outfile.write('\n') 113 | outfile.write('\n') 116 | outfile.write('\n') 117 | outfile.write('\n' % 118 | (self.fontfamily, self.fontsize)) 119 | outfile.write('' % (x, y)) 120 | for ttype, value in tokensource: 121 | style = self._get_style(ttype) 122 | tspan = style and '' or '' 123 | tspanend = tspan and '' or '' 124 | value = escape_html(value) 125 | if self.spacehack: 126 | value = value.expandtabs().replace(' ', ' ') 127 | parts = value.split('\n') 128 | for part in parts[:-1]: 129 | outfile.write(tspan + part + tspanend) 130 | y += self.ystep 131 | outfile.write('\n' % (x, y)) 133 | outfile.write(tspan + parts[-1] + tspanend) 134 | outfile.write('') 135 | 136 | if not self.nowrap: 137 | outfile.write('\n') 138 | 139 | def _get_style(self, tokentype): 140 | if tokentype in self._stylecache: 141 | return self._stylecache[tokentype] 142 | otokentype = tokentype 143 | while not self.style.styles_token(tokentype): 144 | tokentype = tokentype.parent 145 | value = self.style.style_for_token(tokentype) 146 | result = '' 147 | if value['color']: 148 | result = ' fill="#' + value['color'] + '"' 149 | if value['bold']: 150 | result += ' font-weight="bold"' 151 | if value['italic']: 152 | result += ' font-style="italic"' 153 | self._stylecache[otokentype] = result 154 | return result 155 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/terminal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters.terminal 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Formatter for terminal output with ANSI sequences. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | import sys 13 | 14 | from pygments.formatter import Formatter 15 | from pygments.token import Keyword, Name, Comment, String, Error, \ 16 | Number, Operator, Generic, Token, Whitespace 17 | from pygments.console import ansiformat 18 | from pygments.util import get_choice_opt 19 | 20 | 21 | __all__ = ['TerminalFormatter'] 22 | 23 | 24 | #: Map token types to a tuple of color values for light and dark 25 | #: backgrounds. 26 | TERMINAL_COLORS = { 27 | Token: ('', ''), 28 | 29 | Whitespace: ('lightgray', 'darkgray'), 30 | Comment: ('lightgray', 'darkgray'), 31 | Comment.Preproc: ('teal', 'turquoise'), 32 | Keyword: ('darkblue', 'blue'), 33 | Keyword.Type: ('teal', 'turquoise'), 34 | Operator.Word: ('purple', 'fuchsia'), 35 | Name.Builtin: ('teal', 'turquoise'), 36 | Name.Function: ('darkgreen', 'green'), 37 | Name.Namespace: ('_teal_', '_turquoise_'), 38 | Name.Class: ('_darkgreen_', '_green_'), 39 | Name.Exception: ('teal', 'turquoise'), 40 | Name.Decorator: ('darkgray', 'lightgray'), 41 | Name.Variable: ('darkred', 'red'), 42 | Name.Constant: ('darkred', 'red'), 43 | Name.Attribute: ('teal', 'turquoise'), 44 | Name.Tag: ('blue', 'blue'), 45 | String: ('brown', 'brown'), 46 | Number: ('darkblue', 'blue'), 47 | 48 | Generic.Deleted: ('red', 'red'), 49 | Generic.Inserted: ('darkgreen', 'green'), 50 | Generic.Heading: ('**', '**'), 51 | Generic.Subheading: ('*purple*', '*fuchsia*'), 52 | Generic.Error: ('red', 'red'), 53 | 54 | Error: ('_red_', '_red_'), 55 | } 56 | 57 | 58 | class TerminalFormatter(Formatter): 59 | r""" 60 | Format tokens with ANSI color sequences, for output in a text console. 61 | Color sequences are terminated at newlines, so that paging the output 62 | works correctly. 63 | 64 | The `get_style_defs()` method doesn't do anything special since there is 65 | no support for common styles. 66 | 67 | Options accepted: 68 | 69 | `bg` 70 | Set to ``"light"`` or ``"dark"`` depending on the terminal's background 71 | (default: ``"light"``). 72 | 73 | `colorscheme` 74 | A dictionary mapping token types to (lightbg, darkbg) color names or 75 | ``None`` (default: ``None`` = use builtin colorscheme). 76 | """ 77 | name = 'Terminal' 78 | aliases = ['terminal', 'console'] 79 | filenames = [] 80 | 81 | def __init__(self, **options): 82 | Formatter.__init__(self, **options) 83 | self.darkbg = get_choice_opt(options, 'bg', 84 | ['light', 'dark'], 'light') == 'dark' 85 | self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS 86 | 87 | def format(self, tokensource, outfile): 88 | # hack: if the output is a terminal and has an encoding set, 89 | # use that to avoid unicode encode problems 90 | if not self.encoding and hasattr(outfile, "encoding") and \ 91 | hasattr(outfile, "isatty") and outfile.isatty() and \ 92 | sys.version_info < (3,): 93 | self.encoding = outfile.encoding 94 | return Formatter.format(self, tokensource, outfile) 95 | 96 | def format_unencoded(self, tokensource, outfile): 97 | for ttype, value in tokensource: 98 | color = self.colorscheme.get(ttype) 99 | while color is None: 100 | ttype = ttype[:-1] 101 | color = self.colorscheme.get(ttype) 102 | if color: 103 | color = color[self.darkbg] 104 | spl = value.split('\n') 105 | for line in spl[:-1]: 106 | if line: 107 | outfile.write(ansiformat(color, line)) 108 | outfile.write('\n') 109 | if spl[-1]: 110 | outfile.write(ansiformat(color, spl[-1])) 111 | else: 112 | outfile.write(value) 113 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/formatters/terminal256.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.formatters.terminal256 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Formatter for 256-color terminal output with ANSI sequences. 7 | 8 | RGB-to-XTERM color conversion routines adapted from xterm256-conv 9 | tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2) 10 | by Wolfgang Frisch. 11 | 12 | Formatter version 1. 13 | 14 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 15 | :license: BSD, see LICENSE for details. 16 | """ 17 | 18 | # TODO: 19 | # - Options to map style's bold/underline/italic/border attributes 20 | # to some ANSI attrbutes (something like 'italic=underline') 21 | # - An option to output "style RGB to xterm RGB/index" conversion table 22 | # - An option to indicate that we are running in "reverse background" 23 | # xterm. This means that default colors are white-on-black, not 24 | # black-on-while, so colors like "white background" need to be converted 25 | # to "white background, black foreground", etc... 26 | 27 | import sys 28 | 29 | from pygments.formatter import Formatter 30 | 31 | 32 | __all__ = ['Terminal256Formatter'] 33 | 34 | 35 | class EscapeSequence: 36 | def __init__(self, fg=None, bg=None, bold=False, underline=False): 37 | self.fg = fg 38 | self.bg = bg 39 | self.bold = bold 40 | self.underline = underline 41 | 42 | def escape(self, attrs): 43 | if len(attrs): 44 | return "\x1b[" + ";".join(attrs) + "m" 45 | return "" 46 | 47 | def color_string(self): 48 | attrs = [] 49 | if self.fg is not None: 50 | attrs.extend(("38", "5", "%i" % self.fg)) 51 | if self.bg is not None: 52 | attrs.extend(("48", "5", "%i" % self.bg)) 53 | if self.bold: 54 | attrs.append("01") 55 | if self.underline: 56 | attrs.append("04") 57 | return self.escape(attrs) 58 | 59 | def reset_string(self): 60 | attrs = [] 61 | if self.fg is not None: 62 | attrs.append("39") 63 | if self.bg is not None: 64 | attrs.append("49") 65 | if self.bold or self.underline: 66 | attrs.append("00") 67 | return self.escape(attrs) 68 | 69 | class Terminal256Formatter(Formatter): 70 | r""" 71 | Format tokens with ANSI color sequences, for output in a 256-color 72 | terminal or console. Like in `TerminalFormatter` color sequences 73 | are terminated at newlines, so that paging the output works correctly. 74 | 75 | The formatter takes colors from a style defined by the `style` option 76 | and converts them to nearest ANSI 256-color escape sequences. Bold and 77 | underline attributes from the style are preserved (and displayed). 78 | 79 | *New in Pygments 0.9.* 80 | 81 | Options accepted: 82 | 83 | `style` 84 | The style to use, can be a string or a Style subclass (default: 85 | ``'default'``). 86 | """ 87 | name = 'Terminal256' 88 | aliases = ['terminal256', 'console256', '256'] 89 | filenames = [] 90 | 91 | def __init__(self, **options): 92 | Formatter.__init__(self, **options) 93 | 94 | self.xterm_colors = [] 95 | self.best_match = {} 96 | self.style_string = {} 97 | 98 | self.usebold = 'nobold' not in options 99 | self.useunderline = 'nounderline' not in options 100 | 101 | self._build_color_table() # build an RGB-to-256 color conversion table 102 | self._setup_styles() # convert selected style's colors to term. colors 103 | 104 | def _build_color_table(self): 105 | # colors 0..15: 16 basic colors 106 | 107 | self.xterm_colors.append((0x00, 0x00, 0x00)) # 0 108 | self.xterm_colors.append((0xcd, 0x00, 0x00)) # 1 109 | self.xterm_colors.append((0x00, 0xcd, 0x00)) # 2 110 | self.xterm_colors.append((0xcd, 0xcd, 0x00)) # 3 111 | self.xterm_colors.append((0x00, 0x00, 0xee)) # 4 112 | self.xterm_colors.append((0xcd, 0x00, 0xcd)) # 5 113 | self.xterm_colors.append((0x00, 0xcd, 0xcd)) # 6 114 | self.xterm_colors.append((0xe5, 0xe5, 0xe5)) # 7 115 | self.xterm_colors.append((0x7f, 0x7f, 0x7f)) # 8 116 | self.xterm_colors.append((0xff, 0x00, 0x00)) # 9 117 | self.xterm_colors.append((0x00, 0xff, 0x00)) # 10 118 | self.xterm_colors.append((0xff, 0xff, 0x00)) # 11 119 | self.xterm_colors.append((0x5c, 0x5c, 0xff)) # 12 120 | self.xterm_colors.append((0xff, 0x00, 0xff)) # 13 121 | self.xterm_colors.append((0x00, 0xff, 0xff)) # 14 122 | self.xterm_colors.append((0xff, 0xff, 0xff)) # 15 123 | 124 | # colors 16..232: the 6x6x6 color cube 125 | 126 | valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff) 127 | 128 | for i in range(217): 129 | r = valuerange[(i // 36) % 6] 130 | g = valuerange[(i // 6) % 6] 131 | b = valuerange[i % 6] 132 | self.xterm_colors.append((r, g, b)) 133 | 134 | # colors 233..253: grayscale 135 | 136 | for i in range(1, 22): 137 | v = 8 + i * 10 138 | self.xterm_colors.append((v, v, v)) 139 | 140 | def _closest_color(self, r, g, b): 141 | distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff) 142 | match = 0 143 | 144 | for i in range(0, 254): 145 | values = self.xterm_colors[i] 146 | 147 | rd = r - values[0] 148 | gd = g - values[1] 149 | bd = b - values[2] 150 | d = rd*rd + gd*gd + bd*bd 151 | 152 | if d < distance: 153 | match = i 154 | distance = d 155 | return match 156 | 157 | def _color_index(self, color): 158 | index = self.best_match.get(color, None) 159 | if index is None: 160 | try: 161 | rgb = int(str(color), 16) 162 | except ValueError: 163 | rgb = 0 164 | 165 | r = (rgb >> 16) & 0xff 166 | g = (rgb >> 8) & 0xff 167 | b = rgb & 0xff 168 | index = self._closest_color(r, g, b) 169 | self.best_match[color] = index 170 | return index 171 | 172 | def _setup_styles(self): 173 | for ttype, ndef in self.style: 174 | escape = EscapeSequence() 175 | if ndef['color']: 176 | escape.fg = self._color_index(ndef['color']) 177 | if ndef['bgcolor']: 178 | escape.bg = self._color_index(ndef['bgcolor']) 179 | if self.usebold and ndef['bold']: 180 | escape.bold = True 181 | if self.useunderline and ndef['underline']: 182 | escape.underline = True 183 | self.style_string[str(ttype)] = (escape.color_string(), 184 | escape.reset_string()) 185 | 186 | def format(self, tokensource, outfile): 187 | # hack: if the output is a terminal and has an encoding set, 188 | # use that to avoid unicode encode problems 189 | if not self.encoding and hasattr(outfile, "encoding") and \ 190 | hasattr(outfile, "isatty") and outfile.isatty() and \ 191 | sys.version_info < (3,): 192 | self.encoding = outfile.encoding 193 | return Formatter.format(self, tokensource, outfile) 194 | 195 | def format_unencoded(self, tokensource, outfile): 196 | for ttype, value in tokensource: 197 | not_found = True 198 | while ttype and not_found: 199 | try: 200 | #outfile.write( "<" + str(ttype) + ">" ) 201 | on, off = self.style_string[str(ttype)] 202 | 203 | # Like TerminalFormatter, add "reset colors" escape sequence 204 | # on newline. 205 | spl = value.split('\n') 206 | for line in spl[:-1]: 207 | if line: 208 | outfile.write(on + line + off) 209 | outfile.write('\n') 210 | if spl[-1]: 211 | outfile.write(on + spl[-1] + off) 212 | 213 | not_found = False 214 | #outfile.write( '#' + str(ttype) + '#' ) 215 | 216 | except KeyError: 217 | #ottype = ttype 218 | ttype = ttype[:-1] 219 | #outfile.write( '!' + str(ottype) + '->' + str(ttype) + '!' ) 220 | 221 | if not_found: 222 | outfile.write(value) 223 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/lexers/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.lexers 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Pygments lexers. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | import sys 13 | import types 14 | import fnmatch 15 | from os.path import basename 16 | 17 | from pygments.lexers._mapping import LEXERS 18 | from pygments.plugin import find_plugin_lexers 19 | from pygments.util import ClassNotFound, bytes 20 | 21 | 22 | __all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class', 23 | 'guess_lexer'] + LEXERS.keys() 24 | 25 | _lexer_cache = {} 26 | 27 | 28 | def _load_lexers(module_name): 29 | """ 30 | Load a lexer (and all others in the module too). 31 | """ 32 | mod = __import__(module_name, None, None, ['__all__']) 33 | for lexer_name in mod.__all__: 34 | cls = getattr(mod, lexer_name) 35 | _lexer_cache[cls.name] = cls 36 | 37 | 38 | def get_all_lexers(): 39 | """ 40 | Return a generator of tuples in the form ``(name, aliases, 41 | filenames, mimetypes)`` of all know lexers. 42 | """ 43 | for item in LEXERS.itervalues(): 44 | yield item[1:] 45 | for lexer in find_plugin_lexers(): 46 | yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes 47 | 48 | 49 | def find_lexer_class(name): 50 | """ 51 | Lookup a lexer class by name. Return None if not found. 52 | """ 53 | if name in _lexer_cache: 54 | return _lexer_cache[name] 55 | # lookup builtin lexers 56 | for module_name, lname, aliases, _, _ in LEXERS.itervalues(): 57 | if name == lname: 58 | _load_lexers(module_name) 59 | return _lexer_cache[name] 60 | # continue with lexers from setuptools entrypoints 61 | for cls in find_plugin_lexers(): 62 | if cls.name == name: 63 | return cls 64 | 65 | 66 | def get_lexer_by_name(_alias, **options): 67 | """ 68 | Get a lexer by an alias. 69 | """ 70 | # lookup builtin lexers 71 | for module_name, name, aliases, _, _ in LEXERS.itervalues(): 72 | if _alias in aliases: 73 | if name not in _lexer_cache: 74 | _load_lexers(module_name) 75 | return _lexer_cache[name](**options) 76 | # continue with lexers from setuptools entrypoints 77 | for cls in find_plugin_lexers(): 78 | if _alias in cls.aliases: 79 | return cls(**options) 80 | raise ClassNotFound('no lexer for alias %r found' % _alias) 81 | 82 | 83 | def get_lexer_for_filename(_fn, code=None, **options): 84 | """ 85 | Get a lexer for a filename. If multiple lexers match the filename 86 | pattern, use ``analyze_text()`` to figure out which one is more 87 | appropriate. 88 | """ 89 | matches = [] 90 | fn = basename(_fn) 91 | for modname, name, _, filenames, _ in LEXERS.itervalues(): 92 | for filename in filenames: 93 | if fnmatch.fnmatch(fn, filename): 94 | if name not in _lexer_cache: 95 | _load_lexers(modname) 96 | matches.append((_lexer_cache[name], filename)) 97 | for cls in find_plugin_lexers(): 98 | for filename in cls.filenames: 99 | if fnmatch.fnmatch(fn, filename): 100 | matches.append((cls, filename)) 101 | 102 | if sys.version_info > (3,) and isinstance(code, bytes): 103 | # decode it, since all analyse_text functions expect unicode 104 | code = code.decode('latin1') 105 | 106 | def get_rating(info): 107 | cls, filename = info 108 | # explicit patterns get a bonus 109 | bonus = '*' not in filename and 0.5 or 0 110 | # The class _always_ defines analyse_text because it's included in 111 | # the Lexer class. The default implementation returns None which 112 | # gets turned into 0.0. Run scripts/detect_missing_analyse_text.py 113 | # to find lexers which need it overridden. 114 | if code: 115 | return cls.analyse_text(code) + bonus 116 | return bonus 117 | 118 | if matches: 119 | matches.sort(key=get_rating) 120 | #print "Possible lexers, after sort:", matches 121 | return matches[-1][0](**options) 122 | raise ClassNotFound('no lexer for filename %r found' % _fn) 123 | 124 | 125 | def get_lexer_for_mimetype(_mime, **options): 126 | """ 127 | Get a lexer for a mimetype. 128 | """ 129 | for modname, name, _, _, mimetypes in LEXERS.itervalues(): 130 | if _mime in mimetypes: 131 | if name not in _lexer_cache: 132 | _load_lexers(modname) 133 | return _lexer_cache[name](**options) 134 | for cls in find_plugin_lexers(): 135 | if _mime in cls.mimetypes: 136 | return cls(**options) 137 | raise ClassNotFound('no lexer for mimetype %r found' % _mime) 138 | 139 | 140 | def _iter_lexerclasses(): 141 | """ 142 | Return an iterator over all lexer classes. 143 | """ 144 | for key in sorted(LEXERS): 145 | module_name, name = LEXERS[key][:2] 146 | if name not in _lexer_cache: 147 | _load_lexers(module_name) 148 | yield _lexer_cache[name] 149 | for lexer in find_plugin_lexers(): 150 | yield lexer 151 | 152 | 153 | def guess_lexer_for_filename(_fn, _text, **options): 154 | """ 155 | Lookup all lexers that handle those filenames primary (``filenames``) 156 | or secondary (``alias_filenames``). Then run a text analysis for those 157 | lexers and choose the best result. 158 | 159 | usage:: 160 | 161 | >>> from pygments.lexers import guess_lexer_for_filename 162 | >>> guess_lexer_for_filename('hello.html', '<%= @foo %>') 163 | 164 | >>> guess_lexer_for_filename('hello.html', '

{{ title|e }}

') 165 | 166 | >>> guess_lexer_for_filename('style.css', 'a { color: }') 167 | 168 | """ 169 | fn = basename(_fn) 170 | primary = None 171 | matching_lexers = set() 172 | for lexer in _iter_lexerclasses(): 173 | for filename in lexer.filenames: 174 | if fnmatch.fnmatch(fn, filename): 175 | matching_lexers.add(lexer) 176 | primary = lexer 177 | for filename in lexer.alias_filenames: 178 | if fnmatch.fnmatch(fn, filename): 179 | matching_lexers.add(lexer) 180 | if not matching_lexers: 181 | raise ClassNotFound('no lexer for filename %r found' % fn) 182 | if len(matching_lexers) == 1: 183 | return matching_lexers.pop()(**options) 184 | result = [] 185 | for lexer in matching_lexers: 186 | rv = lexer.analyse_text(_text) 187 | if rv == 1.0: 188 | return lexer(**options) 189 | result.append((rv, lexer)) 190 | result.sort() 191 | if not result[-1][0] and primary is not None: 192 | return primary(**options) 193 | return result[-1][1](**options) 194 | 195 | 196 | def guess_lexer(_text, **options): 197 | """ 198 | Guess a lexer by strong distinctions in the text (eg, shebang). 199 | """ 200 | best_lexer = [0.0, None] 201 | for lexer in _iter_lexerclasses(): 202 | rv = lexer.analyse_text(_text) 203 | if rv == 1.0: 204 | return lexer(**options) 205 | if rv > best_lexer[0]: 206 | best_lexer[:] = (rv, lexer) 207 | if not best_lexer[0] or best_lexer[1] is None: 208 | raise ClassNotFound('no lexer matching the text found') 209 | return best_lexer[1](**options) 210 | 211 | 212 | class _automodule(types.ModuleType): 213 | """Automatically import lexers.""" 214 | 215 | def __getattr__(self, name): 216 | info = LEXERS.get(name) 217 | if info: 218 | _load_lexers(info[0]) 219 | cls = _lexer_cache[info[1]] 220 | setattr(self, name, cls) 221 | return cls 222 | raise AttributeError(name) 223 | 224 | 225 | #oldmod = sys.modules['pygments.lexers'] 226 | #newmod = _automodule('pygments.lexers') 227 | #newmod.__dict__.update(oldmod.__dict__) 228 | #sys.modules['pygments.lexers'] = newmod 229 | #del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types 230 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/lexers/_luabuiltins.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.lexers._luabuiltins 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | This file contains the names and modules of lua functions 7 | It is able to re-generate itself, but for adding new functions you 8 | probably have to add some callbacks (see function module_callbacks). 9 | 10 | Do not edit the MODULES dict by hand. 11 | 12 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 13 | :license: BSD, see LICENSE for details. 14 | """ 15 | 16 | MODULES = {'basic': ['_G', 17 | '_VERSION', 18 | 'assert', 19 | 'collectgarbage', 20 | 'dofile', 21 | 'error', 22 | 'getfenv', 23 | 'getmetatable', 24 | 'ipairs', 25 | 'load', 26 | 'loadfile', 27 | 'loadstring', 28 | 'next', 29 | 'pairs', 30 | 'pcall', 31 | 'print', 32 | 'rawequal', 33 | 'rawget', 34 | 'rawset', 35 | 'select', 36 | 'setfenv', 37 | 'setmetatable', 38 | 'tonumber', 39 | 'tostring', 40 | 'type', 41 | 'unpack', 42 | 'xpcall'], 43 | 'coroutine': ['coroutine.create', 44 | 'coroutine.resume', 45 | 'coroutine.running', 46 | 'coroutine.status', 47 | 'coroutine.wrap', 48 | 'coroutine.yield'], 49 | 'debug': ['debug.debug', 50 | 'debug.getfenv', 51 | 'debug.gethook', 52 | 'debug.getinfo', 53 | 'debug.getlocal', 54 | 'debug.getmetatable', 55 | 'debug.getregistry', 56 | 'debug.getupvalue', 57 | 'debug.setfenv', 58 | 'debug.sethook', 59 | 'debug.setlocal', 60 | 'debug.setmetatable', 61 | 'debug.setupvalue', 62 | 'debug.traceback'], 63 | 'io': ['io.close', 64 | 'io.flush', 65 | 'io.input', 66 | 'io.lines', 67 | 'io.open', 68 | 'io.output', 69 | 'io.popen', 70 | 'io.read', 71 | 'io.tmpfile', 72 | 'io.type', 73 | 'io.write'], 74 | 'math': ['math.abs', 75 | 'math.acos', 76 | 'math.asin', 77 | 'math.atan2', 78 | 'math.atan', 79 | 'math.ceil', 80 | 'math.cosh', 81 | 'math.cos', 82 | 'math.deg', 83 | 'math.exp', 84 | 'math.floor', 85 | 'math.fmod', 86 | 'math.frexp', 87 | 'math.huge', 88 | 'math.ldexp', 89 | 'math.log10', 90 | 'math.log', 91 | 'math.max', 92 | 'math.min', 93 | 'math.modf', 94 | 'math.pi', 95 | 'math.pow', 96 | 'math.rad', 97 | 'math.random', 98 | 'math.randomseed', 99 | 'math.sinh', 100 | 'math.sin', 101 | 'math.sqrt', 102 | 'math.tanh', 103 | 'math.tan'], 104 | 'modules': ['module', 105 | 'require', 106 | 'package.cpath', 107 | 'package.loaded', 108 | 'package.loadlib', 109 | 'package.path', 110 | 'package.preload', 111 | 'package.seeall'], 112 | 'os': ['os.clock', 113 | 'os.date', 114 | 'os.difftime', 115 | 'os.execute', 116 | 'os.exit', 117 | 'os.getenv', 118 | 'os.remove', 119 | 'os.rename', 120 | 'os.setlocale', 121 | 'os.time', 122 | 'os.tmpname'], 123 | 'string': ['string.byte', 124 | 'string.char', 125 | 'string.dump', 126 | 'string.find', 127 | 'string.format', 128 | 'string.gmatch', 129 | 'string.gsub', 130 | 'string.len', 131 | 'string.lower', 132 | 'string.match', 133 | 'string.rep', 134 | 'string.reverse', 135 | 'string.sub', 136 | 'string.upper'], 137 | 'table': ['table.concat', 138 | 'table.insert', 139 | 'table.maxn', 140 | 'table.remove', 141 | 'table.sort']} 142 | 143 | if __name__ == '__main__': 144 | import re 145 | import urllib 146 | import pprint 147 | 148 | # you can't generally find out what module a function belongs to if you 149 | # have only its name. Because of this, here are some callback functions 150 | # that recognize if a gioven function belongs to a specific module 151 | def module_callbacks(): 152 | def is_in_coroutine_module(name): 153 | return name.startswith('coroutine.') 154 | 155 | def is_in_modules_module(name): 156 | if name in ['require', 'module'] or name.startswith('package'): 157 | return True 158 | else: 159 | return False 160 | 161 | def is_in_string_module(name): 162 | return name.startswith('string.') 163 | 164 | def is_in_table_module(name): 165 | return name.startswith('table.') 166 | 167 | def is_in_math_module(name): 168 | return name.startswith('math') 169 | 170 | def is_in_io_module(name): 171 | return name.startswith('io.') 172 | 173 | def is_in_os_module(name): 174 | return name.startswith('os.') 175 | 176 | def is_in_debug_module(name): 177 | return name.startswith('debug.') 178 | 179 | return {'coroutine': is_in_coroutine_module, 180 | 'modules': is_in_modules_module, 181 | 'string': is_in_string_module, 182 | 'table': is_in_table_module, 183 | 'math': is_in_math_module, 184 | 'io': is_in_io_module, 185 | 'os': is_in_os_module, 186 | 'debug': is_in_debug_module} 187 | 188 | 189 | 190 | def get_newest_version(): 191 | f = urllib.urlopen('http://www.lua.org/manual/') 192 | r = re.compile(r'^Lua \1') 193 | for line in f: 194 | m = r.match(line) 195 | if m is not None: 196 | return m.groups()[0] 197 | 198 | def get_lua_functions(version): 199 | f = urllib.urlopen('http://www.lua.org/manual/%s/' % version) 200 | r = re.compile(r'^\1') 201 | functions = [] 202 | for line in f: 203 | m = r.match(line) 204 | if m is not None: 205 | functions.append(m.groups()[0]) 206 | return functions 207 | 208 | def get_function_module(name): 209 | for mod, cb in module_callbacks().iteritems(): 210 | if cb(name): 211 | return mod 212 | if '.' in name: 213 | return name.split('.')[0] 214 | else: 215 | return 'basic' 216 | 217 | def regenerate(filename, modules): 218 | f = open(filename) 219 | try: 220 | content = f.read() 221 | finally: 222 | f.close() 223 | 224 | header = content[:content.find('MODULES = {')] 225 | footer = content[content.find("if __name__ == '__main__':"):] 226 | 227 | 228 | f = open(filename, 'w') 229 | f.write(header) 230 | f.write('MODULES = %s\n\n' % pprint.pformat(modules)) 231 | f.write(footer) 232 | f.close() 233 | 234 | def run(): 235 | version = get_newest_version() 236 | print '> Downloading function index for Lua %s' % version 237 | functions = get_lua_functions(version) 238 | print '> %d functions found:' % len(functions) 239 | 240 | modules = {} 241 | for full_function_name in functions: 242 | print '>> %s' % full_function_name 243 | m = get_function_module(full_function_name) 244 | modules.setdefault(m, []).append(full_function_name) 245 | 246 | regenerate(__file__, modules) 247 | 248 | 249 | run() 250 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/lexers/_postgres_builtins.py: -------------------------------------------------------------------------------- 1 | """ 2 | pygments.lexers._postgres_builtins 3 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | Self-updating data files for PostgreSQL lexer. 6 | 7 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 8 | :license: BSD, see LICENSE for details. 9 | """ 10 | 11 | import re 12 | import urllib 13 | 14 | # One man's constant is another man's variable. 15 | SOURCE_URL = 'https://github.com/postgres/postgres/raw/master' 16 | KEYWORDS_URL = SOURCE_URL + '/doc/src/sgml/keywords.sgml' 17 | DATATYPES_URL = SOURCE_URL + '/doc/src/sgml/datatype.sgml' 18 | 19 | def update_myself(): 20 | data_file = list(fetch(DATATYPES_URL)) 21 | datatypes = parse_datatypes(data_file) 22 | pseudos = parse_pseudos(data_file) 23 | 24 | keywords = parse_keywords(fetch(KEYWORDS_URL)) 25 | update_consts(__file__, 'DATATYPES', datatypes) 26 | update_consts(__file__, 'PSEUDO_TYPES', pseudos) 27 | update_consts(__file__, 'KEYWORDS', keywords) 28 | 29 | def parse_keywords(f): 30 | kw = [] 31 | for m in re.finditer( 32 | r'\s*([^<]+)\s*' 33 | r'([^<]+)', f.read()): 34 | kw.append(m.group(1)) 35 | 36 | if not kw: 37 | raise ValueError('no keyword found') 38 | 39 | kw.sort() 40 | return kw 41 | 42 | def parse_datatypes(f): 43 | dt = set() 44 | re_entry = re.compile('\s*([^<]+)') 45 | for line in f: 46 | if '' not in line: 49 | continue 50 | 51 | # Parse a string such as 52 | # time [ (p) ] [ without time zone ] 53 | # into types "time" and "without time zone" 54 | 55 | # remove all the tags 56 | line = re.sub("[^<]+", "", line) 57 | line = re.sub("<[^>]+>", "", line) 58 | 59 | # Drop the parts containing braces 60 | for tmp in [ t for tmp in line.split('[') for t in tmp.split(']') if "(" not in t ]: 61 | for t in tmp.split(','): 62 | t = t.strip() 63 | if not t: continue 64 | dt.add(" ".join(t.split())) 65 | 66 | dt = list(dt) 67 | dt.sort() 68 | return dt 69 | 70 | def parse_pseudos(f): 71 | dt = [] 72 | re_start = re.compile(r'\s*') 73 | re_entry = re.compile(r'\s*([^<]+)') 74 | re_end = re.compile(r'\s*
') 75 | 76 | f = iter(f) 77 | for line in f: 78 | if re_start.match(line) is not None: 79 | break 80 | else: 81 | raise ValueError('pseudo datatypes table not found') 82 | 83 | for line in f: 84 | m = re_entry.match(line) 85 | if m is not None: 86 | dt.append(m.group(1)) 87 | 88 | if re_end.match(line) is not None: 89 | break 90 | else: 91 | raise ValueError('end of pseudo datatypes table not found') 92 | 93 | if not dt: 94 | raise ValueError('pseudo datatypes not found') 95 | 96 | return dt 97 | 98 | def fetch(url): 99 | return urllib.urlopen(url) 100 | 101 | def update_consts(filename, constname, content): 102 | f = open(filename) 103 | lines = f.readlines() 104 | f.close() 105 | 106 | # Line to start/end inserting 107 | re_start = re.compile(r'^%s\s*=\s*\[\s*$' % constname) 108 | re_end = re.compile(r'^\s*\]\s*$') 109 | start = [ n for n, l in enumerate(lines) if re_start.match(l) ] 110 | if not start: 111 | raise ValueError("couldn't find line containing '%s = ['" % constname) 112 | if len(start) > 1: 113 | raise ValueError("too many lines containing '%s = ['" % constname) 114 | start = start[0] + 1 115 | 116 | end = [ n for n, l in enumerate(lines) if n >= start and re_end.match(l) ] 117 | if not end: 118 | raise ValueError("couldn't find line containing ']' after %s " % constname) 119 | end = end[0] 120 | 121 | # Pack the new content in lines not too long 122 | content = [repr(item) for item in content ] 123 | new_lines = [[]] 124 | for item in content: 125 | if sum(map(len, new_lines[-1])) + 2 * len(new_lines[-1]) + len(item) + 4 > 75: 126 | new_lines.append([]) 127 | new_lines[-1].append(item) 128 | 129 | lines[start:end] = [ " %s,\n" % ", ".join(items) for items in new_lines ] 130 | 131 | f = open(filename, 'w') 132 | f.write(''.join(lines)) 133 | f.close() 134 | 135 | 136 | # Autogenerated: please edit them if you like wasting your time. 137 | 138 | KEYWORDS = [ 139 | 'ABORT', 'ABSOLUTE', 'ACCESS', 'ACTION', 'ADD', 'ADMIN', 'AFTER', 140 | 'AGGREGATE', 'ALL', 'ALSO', 'ALTER', 'ALWAYS', 'ANALYSE', 'ANALYZE', 141 | 'AND', 'ANY', 'ARRAY', 'AS', 'ASC', 'ASSERTION', 'ASSIGNMENT', 142 | 'ASYMMETRIC', 'AT', 'ATTRIBUTE', 'AUTHORIZATION', 'BACKWARD', 'BEFORE', 143 | 'BEGIN', 'BETWEEN', 'BIGINT', 'BINARY', 'BIT', 'BOOLEAN', 'BOTH', 'BY', 144 | 'CACHE', 'CALLED', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 145 | 'CHAIN', 'CHAR', 'CHARACTER', 'CHARACTERISTICS', 'CHECK', 'CHECKPOINT', 146 | 'CLASS', 'CLOSE', 'CLUSTER', 'COALESCE', 'COLLATE', 'COLLATION', 147 | 'COLUMN', 'COMMENT', 'COMMENTS', 'COMMIT', 'COMMITTED', 'CONCURRENTLY', 148 | 'CONFIGURATION', 'CONNECTION', 'CONSTRAINT', 'CONSTRAINTS', 'CONTENT', 149 | 'CONTINUE', 'CONVERSION', 'COPY', 'COST', 'CREATE', 'CROSS', 'CSV', 150 | 'CURRENT', 'CURRENT_CATALOG', 'CURRENT_DATE', 'CURRENT_ROLE', 151 | 'CURRENT_SCHEMA', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 152 | 'CURSOR', 'CYCLE', 'DATA', 'DATABASE', 'DAY', 'DEALLOCATE', 'DEC', 153 | 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFAULTS', 'DEFERRABLE', 'DEFERRED', 154 | 'DEFINER', 'DELETE', 'DELIMITER', 'DELIMITERS', 'DESC', 'DICTIONARY', 155 | 'DISABLE', 'DISCARD', 'DISTINCT', 'DO', 'DOCUMENT', 'DOMAIN', 'DOUBLE', 156 | 'DROP', 'EACH', 'ELSE', 'ENABLE', 'ENCODING', 'ENCRYPTED', 'END', 157 | 'ENUM', 'ESCAPE', 'EXCEPT', 'EXCLUDE', 'EXCLUDING', 'EXCLUSIVE', 158 | 'EXECUTE', 'EXISTS', 'EXPLAIN', 'EXTENSION', 'EXTERNAL', 'EXTRACT', 159 | 'FALSE', 'FAMILY', 'FETCH', 'FIRST', 'FLOAT', 'FOLLOWING', 'FOR', 160 | 'FORCE', 'FOREIGN', 'FORWARD', 'FREEZE', 'FROM', 'FULL', 'FUNCTION', 161 | 'FUNCTIONS', 'GLOBAL', 'GRANT', 'GRANTED', 'GREATEST', 'GROUP', 162 | 'HANDLER', 'HAVING', 'HEADER', 'HOLD', 'HOUR', 'IDENTITY', 'IF', 163 | 'ILIKE', 'IMMEDIATE', 'IMMUTABLE', 'IMPLICIT', 'IN', 'INCLUDING', 164 | 'INCREMENT', 'INDEX', 'INDEXES', 'INHERIT', 'INHERITS', 'INITIALLY', 165 | 'INLINE', 'INNER', 'INOUT', 'INPUT', 'INSENSITIVE', 'INSERT', 'INSTEAD', 166 | 'INT', 'INTEGER', 'INTERSECT', 'INTERVAL', 'INTO', 'INVOKER', 'IS', 167 | 'ISNULL', 'ISOLATION', 'JOIN', 'KEY', 'LABEL', 'LANGUAGE', 'LARGE', 168 | 'LAST', 'LC_COLLATE', 'LC_CTYPE', 'LEADING', 'LEAST', 'LEFT', 'LEVEL', 169 | 'LIKE', 'LIMIT', 'LISTEN', 'LOAD', 'LOCAL', 'LOCALTIME', 170 | 'LOCALTIMESTAMP', 'LOCATION', 'LOCK', 'MAPPING', 'MATCH', 'MAXVALUE', 171 | 'MINUTE', 'MINVALUE', 'MODE', 'MONTH', 'MOVE', 'NAME', 'NAMES', 172 | 'NATIONAL', 'NATURAL', 'NCHAR', 'NEXT', 'NO', 'NONE', 'NOT', 'NOTHING', 173 | 'NOTIFY', 'NOTNULL', 'NOWAIT', 'NULL', 'NULLIF', 'NULLS', 'NUMERIC', 174 | 'OBJECT', 'OF', 'OFF', 'OFFSET', 'OIDS', 'ON', 'ONLY', 'OPERATOR', 175 | 'OPTION', 'OPTIONS', 'OR', 'ORDER', 'OUT', 'OUTER', 'OVER', 'OVERLAPS', 176 | 'OVERLAY', 'OWNED', 'OWNER', 'PARSER', 'PARTIAL', 'PARTITION', 177 | 'PASSING', 'PASSWORD', 'PLACING', 'PLANS', 'POSITION', 'PRECEDING', 178 | 'PRECISION', 'PREPARE', 'PREPARED', 'PRESERVE', 'PRIMARY', 'PRIOR', 179 | 'PRIVILEGES', 'PROCEDURAL', 'PROCEDURE', 'QUOTE', 'RANGE', 'READ', 180 | 'REAL', 'REASSIGN', 'RECHECK', 'RECURSIVE', 'REF', 'REFERENCES', 181 | 'REINDEX', 'RELATIVE', 'RELEASE', 'RENAME', 'REPEATABLE', 'REPLACE', 182 | 'REPLICA', 'RESET', 'RESTART', 'RESTRICT', 'RETURNING', 'RETURNS', 183 | 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROW', 'ROWS', 'RULE', 184 | 'SAVEPOINT', 'SCHEMA', 'SCROLL', 'SEARCH', 'SECOND', 'SECURITY', 185 | 'SELECT', 'SEQUENCE', 'SEQUENCES', 'SERIALIZABLE', 'SERVER', 'SESSION', 186 | 'SESSION_USER', 'SET', 'SETOF', 'SHARE', 'SHOW', 'SIMILAR', 'SIMPLE', 187 | 'SMALLINT', 'SOME', 'STABLE', 'STANDALONE', 'START', 'STATEMENT', 188 | 'STATISTICS', 'STDIN', 'STDOUT', 'STORAGE', 'STRICT', 'STRIP', 189 | 'SUBSTRING', 'SYMMETRIC', 'SYSID', 'SYSTEM', 'TABLE', 'TABLES', 190 | 'TABLESPACE', 'TEMP', 'TEMPLATE', 'TEMPORARY', 'TEXT', 'THEN', 'TIME', 191 | 'TIMESTAMP', 'TO', 'TRAILING', 'TRANSACTION', 'TREAT', 'TRIGGER', 192 | 'TRIM', 'TRUE', 'TRUNCATE', 'TRUSTED', 'TYPE', 'UNBOUNDED', 193 | 'UNCOMMITTED', 'UNENCRYPTED', 'UNION', 'UNIQUE', 'UNKNOWN', 'UNLISTEN', 194 | 'UNLOGGED', 'UNTIL', 'UPDATE', 'USER', 'USING', 'VACUUM', 'VALID', 195 | 'VALIDATE', 'VALIDATOR', 'VALUE', 'VALUES', 'VARCHAR', 'VARIADIC', 196 | 'VARYING', 'VERBOSE', 'VERSION', 'VIEW', 'VOLATILE', 'WHEN', 'WHERE', 197 | 'WHITESPACE', 'WINDOW', 'WITH', 'WITHOUT', 'WORK', 'WRAPPER', 'WRITE', 198 | 'XML', 'XMLATTRIBUTES', 'XMLCONCAT', 'XMLELEMENT', 'XMLEXISTS', 199 | 'XMLFOREST', 'XMLPARSE', 'XMLPI', 'XMLROOT', 'XMLSERIALIZE', 'YEAR', 200 | 'YES', 'ZONE', 201 | ] 202 | 203 | DATATYPES = [ 204 | 'bigint', 'bigserial', 'bit', 'bit varying', 'bool', 'boolean', 'box', 205 | 'bytea', 'char', 'character', 'character varying', 'cidr', 'circle', 206 | 'date', 'decimal', 'double precision', 'float4', 'float8', 'inet', 207 | 'int', 'int2', 'int4', 'int8', 'integer', 'interval', 'line', 'lseg', 208 | 'macaddr', 'money', 'numeric', 'path', 'point', 'polygon', 'real', 209 | 'serial', 'serial4', 'serial8', 'smallint', 'text', 'time', 'timestamp', 210 | 'timestamptz', 'timetz', 'tsquery', 'tsvector', 'txid_snapshot', 'uuid', 211 | 'varbit', 'varchar', 'with time zone', 'without time zone', 'xml', 212 | ] 213 | 214 | PSEUDO_TYPES = [ 215 | 'any', 'anyarray', 'anyelement', 'anyenum', 'anynonarray', 'cstring', 216 | 'internal', 'language_handler', 'fdw_handler', 'record', 'trigger', 217 | 'void', 'opaque', 218 | ] 219 | 220 | # Remove 'trigger' from types 221 | PSEUDO_TYPES = sorted(set(PSEUDO_TYPES) - set(map(str.lower, KEYWORDS))) 222 | 223 | PLPGSQL_KEYWORDS = [ 224 | 'ALIAS', 'CONSTANT', 'DIAGNOSTICS', 'ELSIF', 'EXCEPTION', 'EXIT', 225 | 'FOREACH', 'GET', 'LOOP', 'NOTICE', 'OPEN', 'PERFORM', 'QUERY', 'RAISE', 226 | 'RETURN', 'REVERSE', 'SQLSTATE', 'WHILE', 227 | ] 228 | 229 | if __name__ == '__main__': 230 | update_myself() 231 | 232 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/lexers/asm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.lexers.asm 4 | ~~~~~~~~~~~~~~~~~~~ 5 | 6 | Lexers for assembly languages. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | import re 13 | 14 | from pygments.lexer import RegexLexer, include, bygroups, using, DelegatingLexer 15 | from pygments.lexers.compiled import DLexer, CppLexer, CLexer 16 | from pygments.token import Text, Name, Number, String, Comment, Punctuation, \ 17 | Other, Keyword, Operator 18 | 19 | __all__ = ['GasLexer', 'ObjdumpLexer','DObjdumpLexer', 'CppObjdumpLexer', 20 | 'CObjdumpLexer', 'LlvmLexer', 'NasmLexer'] 21 | 22 | 23 | class GasLexer(RegexLexer): 24 | """ 25 | For Gas (AT&T) assembly code. 26 | """ 27 | name = 'GAS' 28 | aliases = ['gas'] 29 | filenames = ['*.s', '*.S'] 30 | mimetypes = ['text/x-gas'] 31 | 32 | #: optional Comment or Whitespace 33 | string = r'"(\\"|[^"])*"' 34 | char = r'[a-zA-Z$._0-9@]' 35 | identifier = r'(?:[a-zA-Z$_]' + char + '*|\.' + char + '+)' 36 | number = r'(?:0[xX][a-zA-Z0-9]+|\d+)' 37 | 38 | tokens = { 39 | 'root': [ 40 | include('whitespace'), 41 | (identifier + ':', Name.Label), 42 | (r'\.' + identifier, Name.Attribute, 'directive-args'), 43 | (r'lock|rep(n?z)?|data\d+', Name.Attribute), 44 | (identifier, Name.Function, 'instruction-args'), 45 | (r'[\r\n]+', Text) 46 | ], 47 | 'directive-args': [ 48 | (identifier, Name.Constant), 49 | (string, String), 50 | ('@' + identifier, Name.Attribute), 51 | (number, Number.Integer), 52 | (r'[\r\n]+', Text, '#pop'), 53 | 54 | (r'#.*?$', Comment, '#pop'), 55 | 56 | include('punctuation'), 57 | include('whitespace') 58 | ], 59 | 'instruction-args': [ 60 | # For objdump-disassembled code, shouldn't occur in 61 | # actual assembler input 62 | ('([a-z0-9]+)( )(<)('+identifier+')(>)', 63 | bygroups(Number.Hex, Text, Punctuation, Name.Constant, 64 | Punctuation)), 65 | ('([a-z0-9]+)( )(<)('+identifier+')([-+])('+number+')(>)', 66 | bygroups(Number.Hex, Text, Punctuation, Name.Constant, 67 | Punctuation, Number.Integer, Punctuation)), 68 | 69 | # Address constants 70 | (identifier, Name.Constant), 71 | (number, Number.Integer), 72 | # Registers 73 | ('%' + identifier, Name.Variable), 74 | # Numeric constants 75 | ('$'+number, Number.Integer), 76 | (r"$'(.|\\')'", String.Char), 77 | (r'[\r\n]+', Text, '#pop'), 78 | (r'#.*?$', Comment, '#pop'), 79 | include('punctuation'), 80 | include('whitespace') 81 | ], 82 | 'whitespace': [ 83 | (r'\n', Text), 84 | (r'\s+', Text), 85 | (r'#.*?\n', Comment) 86 | ], 87 | 'punctuation': [ 88 | (r'[-*,.():]+', Punctuation) 89 | ] 90 | } 91 | 92 | def analyse_text(text): 93 | if re.match(r'^\.(text|data|section)', text, re.M): 94 | return True 95 | elif re.match(r'^\.\w+', text, re.M): 96 | return 0.1 97 | 98 | 99 | class ObjdumpLexer(RegexLexer): 100 | """ 101 | For the output of 'objdump -dr' 102 | """ 103 | name = 'objdump' 104 | aliases = ['objdump'] 105 | filenames = ['*.objdump'] 106 | mimetypes = ['text/x-objdump'] 107 | 108 | hex = r'[0-9A-Za-z]' 109 | 110 | tokens = { 111 | 'root': [ 112 | # File name & format: 113 | ('(.*?)(:)( +file format )(.*?)$', 114 | bygroups(Name.Label, Punctuation, Text, String)), 115 | # Section header 116 | ('(Disassembly of section )(.*?)(:)$', 117 | bygroups(Text, Name.Label, Punctuation)), 118 | # Function labels 119 | # (With offset) 120 | ('('+hex+'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$', 121 | bygroups(Number.Hex, Text, Punctuation, Name.Function, 122 | Punctuation, Number.Hex, Punctuation)), 123 | # (Without offset) 124 | ('('+hex+'+)( )(<)(.*?)(>:)$', 125 | bygroups(Number.Hex, Text, Punctuation, Name.Function, 126 | Punctuation)), 127 | # Code line with disassembled instructions 128 | ('( *)('+hex+r'+:)(\t)((?:'+hex+hex+' )+)( *\t)([a-zA-Z].*?)$', 129 | bygroups(Text, Name.Label, Text, Number.Hex, Text, 130 | using(GasLexer))), 131 | # Code line with ascii 132 | ('( *)('+hex+r'+:)(\t)((?:'+hex+hex+' )+)( *)(.*?)$', 133 | bygroups(Text, Name.Label, Text, Number.Hex, Text, String)), 134 | # Continued code line, only raw opcodes without disassembled 135 | # instruction 136 | ('( *)('+hex+r'+:)(\t)((?:'+hex+hex+' )+)$', 137 | bygroups(Text, Name.Label, Text, Number.Hex)), 138 | # Skipped a few bytes 139 | ('\t\.\.\.$', Text), 140 | # Relocation line 141 | # (With offset) 142 | ('(\t\t\t)('+hex+'+:)( )([^\t]+)(\t)(.*?)([-+])(0x' + hex + '+)$', 143 | bygroups(Text, Name.Label, Text, Name.Property, Text, 144 | Name.Constant, Punctuation, Number.Hex)), 145 | # (Without offset) 146 | ('(\t\t\t)('+hex+'+:)( )([^\t]+)(\t)(.*?)$', 147 | bygroups(Text, Name.Label, Text, Name.Property, Text, 148 | Name.Constant)), 149 | ('[^\n]+\n', Other) 150 | ] 151 | } 152 | 153 | 154 | class DObjdumpLexer(DelegatingLexer): 155 | """ 156 | For the output of 'objdump -Sr on compiled D files' 157 | """ 158 | name = 'd-objdump' 159 | aliases = ['d-objdump'] 160 | filenames = ['*.d-objdump'] 161 | mimetypes = ['text/x-d-objdump'] 162 | 163 | def __init__(self, **options): 164 | super(DObjdumpLexer, self).__init__(DLexer, ObjdumpLexer, **options) 165 | 166 | 167 | class CppObjdumpLexer(DelegatingLexer): 168 | """ 169 | For the output of 'objdump -Sr on compiled C++ files' 170 | """ 171 | name = 'cpp-objdump' 172 | aliases = ['cpp-objdump', 'c++-objdumb', 'cxx-objdump'] 173 | filenames = ['*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump'] 174 | mimetypes = ['text/x-cpp-objdump'] 175 | 176 | def __init__(self, **options): 177 | super(CppObjdumpLexer, self).__init__(CppLexer, ObjdumpLexer, **options) 178 | 179 | 180 | class CObjdumpLexer(DelegatingLexer): 181 | """ 182 | For the output of 'objdump -Sr on compiled C files' 183 | """ 184 | name = 'c-objdump' 185 | aliases = ['c-objdump'] 186 | filenames = ['*.c-objdump'] 187 | mimetypes = ['text/x-c-objdump'] 188 | 189 | def __init__(self, **options): 190 | super(CObjdumpLexer, self).__init__(CLexer, ObjdumpLexer, **options) 191 | 192 | 193 | class LlvmLexer(RegexLexer): 194 | """ 195 | For LLVM assembly code. 196 | """ 197 | name = 'LLVM' 198 | aliases = ['llvm'] 199 | filenames = ['*.ll'] 200 | mimetypes = ['text/x-llvm'] 201 | 202 | #: optional Comment or Whitespace 203 | string = r'"[^"]*?"' 204 | identifier = r'([-a-zA-Z$._][-a-zA-Z$._0-9]*|' + string + ')' 205 | 206 | tokens = { 207 | 'root': [ 208 | include('whitespace'), 209 | 210 | # Before keywords, because keywords are valid label names :(... 211 | (r'^\s*' + identifier + '\s*:', Name.Label), 212 | 213 | include('keyword'), 214 | 215 | (r'%' + identifier, Name.Variable),#Name.Identifier.Local), 216 | (r'@' + identifier, Name.Variable.Global),#Name.Identifier.Global), 217 | (r'%\d+', Name.Variable.Anonymous),#Name.Identifier.Anonymous), 218 | (r'@\d+', Name.Variable.Global),#Name.Identifier.Anonymous), 219 | (r'!' + identifier, Name.Variable), 220 | (r'!\d+', Name.Variable.Anonymous), 221 | (r'c?' + string, String), 222 | 223 | (r'0[xX][a-fA-F0-9]+', Number), 224 | (r'-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?', Number), 225 | 226 | (r'[=<>{}\[\]()*.,!]|x\b', Punctuation) 227 | ], 228 | 'whitespace': [ 229 | (r'(\n|\s)+', Text), 230 | (r';.*?\n', Comment) 231 | ], 232 | 'keyword': [ 233 | # Regular keywords 234 | (r'(begin|end' 235 | r'|true|false' 236 | r'|declare|define' 237 | r'|global|constant' 238 | 239 | r'|private|linker_private|internal|available_externally|linkonce' 240 | r'|linkonce_odr|weak|weak_odr|appending|dllimport|dllexport' 241 | r'|common|default|hidden|protected|extern_weak|external' 242 | r'|thread_local|zeroinitializer|undef|null|to|tail|target|triple' 243 | r'|deplibs|datalayout|volatile|nuw|nsw|exact|inbounds|align' 244 | r'|addrspace|section|alias|module|asm|sideeffect|gc|dbg' 245 | 246 | r'|ccc|fastcc|coldcc|x86_stdcallcc|x86_fastcallcc|arm_apcscc' 247 | r'|arm_aapcscc|arm_aapcs_vfpcc' 248 | 249 | r'|cc|c' 250 | 251 | r'|signext|zeroext|inreg|sret|nounwind|noreturn|noalias|nocapture' 252 | r'|byval|nest|readnone|readonly' 253 | 254 | r'|inlinehint|noinline|alwaysinline|optsize|ssp|sspreq|noredzone' 255 | r'|noimplicitfloat|naked' 256 | 257 | r'|type|opaque' 258 | 259 | r'|eq|ne|slt|sgt|sle' 260 | r'|sge|ult|ugt|ule|uge' 261 | r'|oeq|one|olt|ogt|ole' 262 | r'|oge|ord|uno|ueq|une' 263 | r'|x' 264 | 265 | # instructions 266 | r'|add|fadd|sub|fsub|mul|fmul|udiv|sdiv|fdiv|urem|srem|frem|shl' 267 | r'|lshr|ashr|and|or|xor|icmp|fcmp' 268 | 269 | r'|phi|call|trunc|zext|sext|fptrunc|fpext|uitofp|sitofp|fptoui' 270 | r'fptosi|inttoptr|ptrtoint|bitcast|select|va_arg|ret|br|switch' 271 | r'|invoke|unwind|unreachable' 272 | 273 | r'|malloc|alloca|free|load|store|getelementptr' 274 | 275 | r'|extractelement|insertelement|shufflevector|getresult' 276 | r'|extractvalue|insertvalue' 277 | 278 | r')\b', Keyword), 279 | 280 | # Types 281 | (r'void|float|double|x86_fp80|fp128|ppc_fp128|label|metadata', 282 | Keyword.Type), 283 | 284 | # Integer types 285 | (r'i[1-9]\d*', Keyword) 286 | ] 287 | } 288 | 289 | 290 | class NasmLexer(RegexLexer): 291 | """ 292 | For Nasm (Intel) assembly code. 293 | """ 294 | name = 'NASM' 295 | aliases = ['nasm'] 296 | filenames = ['*.asm', '*.ASM'] 297 | mimetypes = ['text/x-nasm'] 298 | 299 | identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?#@~]*' 300 | hexn = r'(?:0[xX][0-9a-fA-F]+|$0[0-9a-fA-F]*|[0-9]+[0-9a-fA-F]*h)' 301 | octn = r'[0-7]+q' 302 | binn = r'[01]+b' 303 | decn = r'[0-9]+' 304 | floatn = decn + r'\.e?' + decn 305 | string = r'"(\\"|[^"])*"|' + r"'(\\'|[^'])*'" 306 | declkw = r'(?:res|d)[bwdqt]|times' 307 | register = (r'[a-d][lh]|e?[a-d]x|e?[sb]p|e?[sd]i|[c-gs]s|st[0-7]|' 308 | r'mm[0-7]|cr[0-4]|dr[0-367]|tr[3-7]') 309 | wordop = r'seg|wrt|strict' 310 | type = r'byte|[dq]?word' 311 | directives = (r'BITS|USE16|USE32|SECTION|SEGMENT|ABSOLUTE|EXTERN|GLOBAL|' 312 | r'ORG|ALIGN|STRUC|ENDSTRUC|COMMON|CPU|GROUP|UPPERCASE|IMPORT|' 313 | r'EXPORT|LIBRARY|MODULE') 314 | 315 | flags = re.IGNORECASE | re.MULTILINE 316 | tokens = { 317 | 'root': [ 318 | include('whitespace'), 319 | (r'^\s*%', Comment.Preproc, 'preproc'), 320 | (identifier + ':', Name.Label), 321 | (r'(%s)(\s+)(equ)' % identifier, 322 | bygroups(Name.Constant, Keyword.Declaration, Keyword.Declaration), 323 | 'instruction-args'), 324 | (directives, Keyword, 'instruction-args'), 325 | (declkw, Keyword.Declaration, 'instruction-args'), 326 | (identifier, Name.Function, 'instruction-args'), 327 | (r'[\r\n]+', Text) 328 | ], 329 | 'instruction-args': [ 330 | (string, String), 331 | (hexn, Number.Hex), 332 | (octn, Number.Oct), 333 | (binn, Number), 334 | (floatn, Number.Float), 335 | (decn, Number.Integer), 336 | include('punctuation'), 337 | (register, Name.Builtin), 338 | (identifier, Name.Variable), 339 | (r'[\r\n]+', Text, '#pop'), 340 | include('whitespace') 341 | ], 342 | 'preproc': [ 343 | (r'[^;\n]+', Comment.Preproc), 344 | (r';.*?\n', Comment.Single, '#pop'), 345 | (r'\n', Comment.Preproc, '#pop'), 346 | ], 347 | 'whitespace': [ 348 | (r'\n', Text), 349 | (r'[ \t]+', Text), 350 | (r';.*', Comment.Single) 351 | ], 352 | 'punctuation': [ 353 | (r'[,():\[\]]+', Punctuation), 354 | (r'[&|^<>+*/%~-]+', Operator), 355 | (r'[$]+', Keyword.Constant), 356 | (wordop, Operator.Word), 357 | (type, Keyword.Type) 358 | ], 359 | } 360 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/lexers/shell.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.lexers.shell 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Lexers for various shells. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | import re 13 | 14 | from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, include 15 | from pygments.token import Punctuation, \ 16 | Text, Comment, Operator, Keyword, Name, String, Number, Generic 17 | from pygments.util import shebang_matches 18 | 19 | 20 | __all__ = ['BashLexer', 'BashSessionLexer', 'TcshLexer', 'BatchLexer', 21 | 'PowerShellLexer'] 22 | 23 | line_re = re.compile('.*?\n') 24 | 25 | 26 | class BashLexer(RegexLexer): 27 | """ 28 | Lexer for (ba|k|)sh shell scripts. 29 | 30 | *New in Pygments 0.6.* 31 | """ 32 | 33 | name = 'Bash' 34 | aliases = ['bash', 'sh', 'ksh'] 35 | filenames = ['*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass'] 36 | mimetypes = ['application/x-sh', 'application/x-shellscript'] 37 | 38 | tokens = { 39 | 'root': [ 40 | include('basic'), 41 | (r'\$\(\(', Keyword, 'math'), 42 | (r'\$\(', Keyword, 'paren'), 43 | (r'\${#?', Keyword, 'curly'), 44 | (r'`', String.Backtick, 'backticks'), 45 | include('data'), 46 | ], 47 | 'basic': [ 48 | (r'\b(if|fi|else|while|do|done|for|then|return|function|case|' 49 | r'select|continue|until|esac|elif)\s*\b', 50 | Keyword), 51 | (r'\b(alias|bg|bind|break|builtin|caller|cd|command|compgen|' 52 | r'complete|declare|dirs|disown|echo|enable|eval|exec|exit|' 53 | r'export|false|fc|fg|getopts|hash|help|history|jobs|kill|let|' 54 | r'local|logout|popd|printf|pushd|pwd|read|readonly|set|shift|' 55 | r'shopt|source|suspend|test|time|times|trap|true|type|typeset|' 56 | r'ulimit|umask|unalias|unset|wait)\s*\b(?!\.)', 57 | Name.Builtin), 58 | (r'#.*\n', Comment), 59 | (r'\\[\w\W]', String.Escape), 60 | (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)), 61 | (r'[\[\]{}()=]', Operator), 62 | (r'<<-?\s*(\'?)\\?(\w+)[\w\W]+?\2', String), 63 | (r'&&|\|\|', Operator), 64 | ], 65 | 'data': [ 66 | (r'(?s)\$?"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double), 67 | (r"(?s)\$?'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single), 68 | (r';', Text), 69 | (r'\s+', Text), 70 | (r'[^=\s\n\[\]{}()$"\'`\\<]+', Text), 71 | (r'\d+(?= |\Z)', Number), 72 | (r'\$#?(\w+|.)', Name.Variable), 73 | (r'<', Text), 74 | ], 75 | 'curly': [ 76 | (r'}', Keyword, '#pop'), 77 | (r':-', Keyword), 78 | (r'[a-zA-Z0-9_]+', Name.Variable), 79 | (r'[^}:"\'`$]+', Punctuation), 80 | (r':', Punctuation), 81 | include('root'), 82 | ], 83 | 'paren': [ 84 | (r'\)', Keyword, '#pop'), 85 | include('root'), 86 | ], 87 | 'math': [ 88 | (r'\)\)', Keyword, '#pop'), 89 | (r'[-+*/%^|&]|\*\*|\|\|', Operator), 90 | (r'\d+', Number), 91 | include('root'), 92 | ], 93 | 'backticks': [ 94 | (r'`', String.Backtick, '#pop'), 95 | include('root'), 96 | ], 97 | } 98 | 99 | def analyse_text(text): 100 | return shebang_matches(text, r'(ba|z|)sh') 101 | 102 | 103 | class BashSessionLexer(Lexer): 104 | """ 105 | Lexer for simplistic shell sessions. 106 | 107 | *New in Pygments 1.1.* 108 | """ 109 | 110 | name = 'Bash Session' 111 | aliases = ['console'] 112 | filenames = ['*.sh-session'] 113 | mimetypes = ['application/x-shell-session'] 114 | 115 | def get_tokens_unprocessed(self, text): 116 | bashlexer = BashLexer(**self.options) 117 | 118 | pos = 0 119 | curcode = '' 120 | insertions = [] 121 | 122 | for match in line_re.finditer(text): 123 | line = match.group() 124 | m = re.match(r'^((?:|sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)?|\[\S+[@:]' 125 | r'[^\n]+\].+)[$#%])(.*\n?)', line) 126 | if m: 127 | # To support output lexers (say diff output), the output 128 | # needs to be broken by prompts whenever the output lexer 129 | # changes. 130 | if not insertions: 131 | pos = match.start() 132 | 133 | insertions.append((len(curcode), 134 | [(0, Generic.Prompt, m.group(1))])) 135 | curcode += m.group(2) 136 | elif line.startswith('>'): 137 | insertions.append((len(curcode), 138 | [(0, Generic.Prompt, line[:1])])) 139 | curcode += line[1:] 140 | else: 141 | if insertions: 142 | toks = bashlexer.get_tokens_unprocessed(curcode) 143 | for i, t, v in do_insertions(insertions, toks): 144 | yield pos+i, t, v 145 | yield match.start(), Generic.Output, line 146 | insertions = [] 147 | curcode = '' 148 | if insertions: 149 | for i, t, v in do_insertions(insertions, 150 | bashlexer.get_tokens_unprocessed(curcode)): 151 | yield pos+i, t, v 152 | 153 | 154 | class BatchLexer(RegexLexer): 155 | """ 156 | Lexer for the DOS/Windows Batch file format. 157 | 158 | *New in Pygments 0.7.* 159 | """ 160 | name = 'Batchfile' 161 | aliases = ['bat'] 162 | filenames = ['*.bat', '*.cmd'] 163 | mimetypes = ['application/x-dos-batch'] 164 | 165 | flags = re.MULTILINE | re.IGNORECASE 166 | 167 | tokens = { 168 | 'root': [ 169 | # Lines can start with @ to prevent echo 170 | (r'^\s*@', Punctuation), 171 | (r'^(\s*)(rem\s.*)$', bygroups(Text, Comment)), 172 | (r'".*?"', String.Double), 173 | (r"'.*?'", String.Single), 174 | # If made more specific, make sure you still allow expansions 175 | # like %~$VAR:zlt 176 | (r'%%?[~$:\w]+%?', Name.Variable), 177 | (r'::.*', Comment), # Technically :: only works at BOL 178 | (r'(set)(\s+)(\w+)', bygroups(Keyword, Text, Name.Variable)), 179 | (r'(call)(\s+)(:\w+)', bygroups(Keyword, Text, Name.Label)), 180 | (r'(goto)(\s+)(\w+)', bygroups(Keyword, Text, Name.Label)), 181 | (r'\b(set|call|echo|on|off|endlocal|for|do|goto|if|pause|' 182 | r'setlocal|shift|errorlevel|exist|defined|cmdextversion|' 183 | r'errorlevel|else|cd|md|del|deltree|cls|choice)\b', Keyword), 184 | (r'\b(equ|neq|lss|leq|gtr|geq)\b', Operator), 185 | include('basic'), 186 | (r'.', Text), 187 | ], 188 | 'echo': [ 189 | # Escapes only valid within echo args? 190 | (r'\^\^|\^<|\^>|\^\|', String.Escape), 191 | (r'\n', Text, '#pop'), 192 | include('basic'), 193 | (r'[^\'"^]+', Text), 194 | ], 195 | 'basic': [ 196 | (r'".*?"', String.Double), 197 | (r"'.*?'", String.Single), 198 | (r'`.*?`', String.Backtick), 199 | (r'-?\d+', Number), 200 | (r',', Punctuation), 201 | (r'=', Operator), 202 | (r'/\S+', Name), 203 | (r':\w+', Name.Label), 204 | (r'\w:\w+', Text), 205 | (r'([<>|])(\s*)(\w+)', bygroups(Punctuation, Text, Name)), 206 | ], 207 | } 208 | 209 | 210 | class TcshLexer(RegexLexer): 211 | """ 212 | Lexer for tcsh scripts. 213 | 214 | *New in Pygments 0.10.* 215 | """ 216 | 217 | name = 'Tcsh' 218 | aliases = ['tcsh', 'csh'] 219 | filenames = ['*.tcsh', '*.csh'] 220 | mimetypes = ['application/x-csh'] 221 | 222 | tokens = { 223 | 'root': [ 224 | include('basic'), 225 | (r'\$\(', Keyword, 'paren'), 226 | (r'\${#?', Keyword, 'curly'), 227 | (r'`', String.Backtick, 'backticks'), 228 | include('data'), 229 | ], 230 | 'basic': [ 231 | (r'\b(if|endif|else|while|then|foreach|case|default|' 232 | r'continue|goto|breaksw|end|switch|endsw)\s*\b', 233 | Keyword), 234 | (r'\b(alias|alloc|bg|bindkey|break|builtins|bye|caller|cd|chdir|' 235 | r'complete|dirs|echo|echotc|eval|exec|exit|fg|filetest|getxvers|' 236 | r'glob|getspath|hashstat|history|hup|inlib|jobs|kill|' 237 | r'limit|log|login|logout|ls-F|migrate|newgrp|nice|nohup|notify|' 238 | r'onintr|popd|printenv|pushd|rehash|repeat|rootnode|popd|pushd|' 239 | r'set|shift|sched|setenv|setpath|settc|setty|setxvers|shift|' 240 | r'source|stop|suspend|source|suspend|telltc|time|' 241 | r'umask|unalias|uncomplete|unhash|universe|unlimit|unset|unsetenv|' 242 | r'ver|wait|warp|watchlog|where|which)\s*\b', 243 | Name.Builtin), 244 | (r'#.*\n', Comment), 245 | (r'\\[\w\W]', String.Escape), 246 | (r'(\b\w+)(\s*)(=)', bygroups(Name.Variable, Text, Operator)), 247 | (r'[\[\]{}()=]+', Operator), 248 | (r'<<\s*(\'?)\\?(\w+)[\w\W]+?\2', String), 249 | ], 250 | 'data': [ 251 | (r'(?s)"(\\\\|\\[0-7]+|\\.|[^"\\])*"', String.Double), 252 | (r"(?s)'(\\\\|\\[0-7]+|\\.|[^'\\])*'", String.Single), 253 | (r'\s+', Text), 254 | (r'[^=\s\n\[\]{}()$"\'`\\]+', Text), 255 | (r'\d+(?= |\Z)', Number), 256 | (r'\$#?(\w+|.)', Name.Variable), 257 | ], 258 | 'curly': [ 259 | (r'}', Keyword, '#pop'), 260 | (r':-', Keyword), 261 | (r'[a-zA-Z0-9_]+', Name.Variable), 262 | (r'[^}:"\'`$]+', Punctuation), 263 | (r':', Punctuation), 264 | include('root'), 265 | ], 266 | 'paren': [ 267 | (r'\)', Keyword, '#pop'), 268 | include('root'), 269 | ], 270 | 'backticks': [ 271 | (r'`', String.Backtick, '#pop'), 272 | include('root'), 273 | ], 274 | } 275 | 276 | 277 | class PowerShellLexer(RegexLexer): 278 | """ 279 | For Windows PowerShell code. 280 | 281 | *New in Pygments 1.5.* 282 | """ 283 | name = 'PowerShell' 284 | aliases = ['powershell', 'posh', 'ps1'] 285 | filenames = ['*.ps1'] 286 | mimetypes = ['text/x-powershell'] 287 | 288 | flags = re.DOTALL | re.IGNORECASE | re.MULTILINE 289 | 290 | keywords = ( 291 | 'while validateset validaterange validatepattern validatelength ' 292 | 'validatecount until trap switch return ref process param parameter in ' 293 | 'if global: function foreach for finally filter end elseif else ' 294 | 'dynamicparam do default continue cmdletbinding break begin alias \\? ' 295 | '% #script #private #local #global mandatory parametersetname position ' 296 | 'valuefrompipeline valuefrompipelinebypropertyname ' 297 | 'valuefromremainingarguments helpmessage try catch').split() 298 | 299 | operators = ( 300 | 'and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle ' 301 | 'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains ' 302 | 'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt ' 303 | 'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like ' 304 | 'lt match ne not notcontains notlike notmatch or regex replace ' 305 | 'wildcard').split() 306 | 307 | verbs = ( 308 | 'write where wait use update unregister undo trace test tee take ' 309 | 'suspend stop start split sort skip show set send select scroll resume ' 310 | 'restore restart resolve resize reset rename remove register receive ' 311 | 'read push pop ping out new move measure limit join invoke import ' 312 | 'group get format foreach export expand exit enter enable disconnect ' 313 | 'disable debug cxnew copy convertto convertfrom convert connect ' 314 | 'complete compare clear checkpoint aggregate add').split() 315 | 316 | commenthelp = ( 317 | 'component description example externalhelp forwardhelpcategory ' 318 | 'forwardhelptargetname forwardhelptargetname functionality inputs link ' 319 | 'notes outputs parameter remotehelprunspace role synopsis').split() 320 | 321 | tokens = { 322 | 'root': [ 323 | (r'\s+', Text), 324 | (r'^(\s*#[#\s]*)(\.(?:%s))([^\n]*$)' % '|'.join(commenthelp), 325 | bygroups(Comment, String.Doc, Comment)), 326 | (r'#[^\n]*?$', Comment), 327 | (r'(<|<)#', Comment.Multiline, 'multline'), 328 | (r'@"\n.*?\n"@', String.Heredoc), 329 | (r"@'\n.*?\n'@", String.Heredoc), 330 | (r'"', String.Double, 'string'), 331 | (r"'([^']|'')*'", String.Single), 332 | (r'(\$|@@|@)((global|script|private|env):)?[a-z0-9_]+', 333 | Name.Variable), 334 | (r'(%s)\b' % '|'.join(keywords), Keyword), 335 | (r'-(%s)\b' % '|'.join(operators), Operator), 336 | (r'(%s)-[a-z_][a-z0-9_]*\b' % '|'.join(verbs), Name.Builtin), 337 | (r'\[[a-z_\[][a-z0-9_. `,\[\]]*\]', Name.Constant), # .net [type]s 338 | (r'-[a-z_][a-z0-9_]*', Name), 339 | (r'\w+', Name), 340 | (r'[.,{}\[\]$()=+*/\\&%!~?^`|<>-]', Punctuation), 341 | ], 342 | 'multline': [ 343 | (r'[^#&.]+', Comment.Multiline), 344 | (r'#(>|>)', Comment.Multiline, '#pop'), 345 | (r'\.(%s)' % '|'.join(commenthelp), String.Doc), 346 | (r'[#&.]', Comment.Multiline), 347 | ], 348 | 'string': [ 349 | (r'[^$`"]+', String.Double), 350 | (r'\$\(', String.Interpol, 'interpol'), 351 | (r'`"|""', String.Double), 352 | (r'[`$]', String.Double), 353 | (r'"', String.Double, '#pop'), 354 | ], 355 | 'interpol': [ 356 | (r'[^$)]+', String.Interpol), 357 | (r'\$\(', String.Interpol, '#push'), 358 | (r'\)', String.Interpol, '#pop'), 359 | ] 360 | } 361 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/lexers/special.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.lexers.special 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Special lexers. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | import re 13 | import cStringIO 14 | 15 | from pygments.lexer import Lexer 16 | from pygments.token import Token, Error, Text 17 | from pygments.util import get_choice_opt, b 18 | 19 | 20 | __all__ = ['TextLexer', 'RawTokenLexer'] 21 | 22 | 23 | class TextLexer(Lexer): 24 | """ 25 | "Null" lexer, doesn't highlight anything. 26 | """ 27 | name = 'Text only' 28 | aliases = ['text'] 29 | filenames = ['*.txt'] 30 | mimetypes = ['text/plain'] 31 | 32 | def get_tokens_unprocessed(self, text): 33 | yield 0, Text, text 34 | 35 | 36 | _ttype_cache = {} 37 | 38 | line_re = re.compile(b('.*?\n')) 39 | 40 | class RawTokenLexer(Lexer): 41 | """ 42 | Recreate a token stream formatted with the `RawTokenFormatter`. This 43 | lexer raises exceptions during parsing if the token stream in the 44 | file is malformed. 45 | 46 | Additional options accepted: 47 | 48 | `compress` 49 | If set to ``"gz"`` or ``"bz2"``, decompress the token stream with 50 | the given compression algorithm before lexing (default: ``""``). 51 | """ 52 | name = 'Raw token data' 53 | aliases = ['raw'] 54 | filenames = [] 55 | mimetypes = ['application/x-pygments-tokens'] 56 | 57 | def __init__(self, **options): 58 | self.compress = get_choice_opt(options, 'compress', 59 | ['', 'none', 'gz', 'bz2'], '') 60 | Lexer.__init__(self, **options) 61 | 62 | def get_tokens(self, text): 63 | if isinstance(text, unicode): 64 | # raw token stream never has any non-ASCII characters 65 | text = text.encode('ascii') 66 | if self.compress == 'gz': 67 | import gzip 68 | gzipfile = gzip.GzipFile('', 'rb', 9, cStringIO.StringIO(text)) 69 | text = gzipfile.read() 70 | elif self.compress == 'bz2': 71 | import bz2 72 | text = bz2.decompress(text) 73 | 74 | # do not call Lexer.get_tokens() because we do not want Unicode 75 | # decoding to occur, and stripping is not optional. 76 | text = text.strip(b('\n')) + b('\n') 77 | for i, t, v in self.get_tokens_unprocessed(text): 78 | yield t, v 79 | 80 | def get_tokens_unprocessed(self, text): 81 | length = 0 82 | for match in line_re.finditer(text): 83 | try: 84 | ttypestr, val = match.group().split(b('\t'), 1) 85 | except ValueError: 86 | val = match.group().decode(self.encoding) 87 | ttype = Error 88 | else: 89 | ttype = _ttype_cache.get(ttypestr) 90 | if not ttype: 91 | ttype = Token 92 | ttypes = ttypestr.split('.')[1:] 93 | for ttype_ in ttypes: 94 | if not ttype_ or not ttype_[0].isupper(): 95 | raise ValueError('malformed token name') 96 | ttype = getattr(ttype, ttype_) 97 | _ttype_cache[ttypestr] = ttype 98 | val = val[2:-2].decode('unicode-escape') 99 | yield length, ttype, val 100 | length += len(val) 101 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/plugin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.plugin 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Pygments setuptools plugin interface. The methods defined 7 | here also work if setuptools isn't installed but they just 8 | return nothing. 9 | 10 | lexer plugins:: 11 | 12 | [pygments.lexers] 13 | yourlexer = yourmodule:YourLexer 14 | 15 | formatter plugins:: 16 | 17 | [pygments.formatters] 18 | yourformatter = yourformatter:YourFormatter 19 | /.ext = yourformatter:YourFormatter 20 | 21 | As you can see, you can define extensions for the formatter 22 | with a leading slash. 23 | 24 | syntax plugins:: 25 | 26 | [pygments.styles] 27 | yourstyle = yourstyle:YourStyle 28 | 29 | filter plugin:: 30 | 31 | [pygments.filter] 32 | yourfilter = yourfilter:YourFilter 33 | 34 | 35 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 36 | :license: BSD, see LICENSE for details. 37 | """ 38 | try: 39 | import pkg_resources 40 | except ImportError: 41 | pkg_resources = None 42 | 43 | LEXER_ENTRY_POINT = 'pygments.lexers' 44 | FORMATTER_ENTRY_POINT = 'pygments.formatters' 45 | STYLE_ENTRY_POINT = 'pygments.styles' 46 | FILTER_ENTRY_POINT = 'pygments.filters' 47 | 48 | 49 | def find_plugin_lexers(): 50 | if pkg_resources is None: 51 | return 52 | for entrypoint in pkg_resources.iter_entry_points(LEXER_ENTRY_POINT): 53 | yield entrypoint.load() 54 | 55 | 56 | def find_plugin_formatters(): 57 | if pkg_resources is None: 58 | return 59 | for entrypoint in pkg_resources.iter_entry_points(FORMATTER_ENTRY_POINT): 60 | yield entrypoint.name, entrypoint.load() 61 | 62 | 63 | def find_plugin_styles(): 64 | if pkg_resources is None: 65 | return 66 | for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT): 67 | yield entrypoint.name, entrypoint.load() 68 | 69 | 70 | def find_plugin_filters(): 71 | if pkg_resources is None: 72 | return 73 | for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT): 74 | yield entrypoint.name, entrypoint.load() 75 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/scanner.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.scanner 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | This library implements a regex based scanner. Some languages 7 | like Pascal are easy to parse but have some keywords that 8 | depend on the context. Because of this it's impossible to lex 9 | that just by using a regular expression lexer like the 10 | `RegexLexer`. 11 | 12 | Have a look at the `DelphiLexer` to get an idea of how to use 13 | this scanner. 14 | 15 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 16 | :license: BSD, see LICENSE for details. 17 | """ 18 | import re 19 | 20 | 21 | class EndOfText(RuntimeError): 22 | """ 23 | Raise if end of text is reached and the user 24 | tried to call a match function. 25 | """ 26 | 27 | 28 | class Scanner(object): 29 | """ 30 | Simple scanner 31 | 32 | All method patterns are regular expression strings (not 33 | compiled expressions!) 34 | """ 35 | 36 | def __init__(self, text, flags=0): 37 | """ 38 | :param text: The text which should be scanned 39 | :param flags: default regular expression flags 40 | """ 41 | self.data = text 42 | self.data_length = len(text) 43 | self.start_pos = 0 44 | self.pos = 0 45 | self.flags = flags 46 | self.last = None 47 | self.match = None 48 | self._re_cache = {} 49 | 50 | def eos(self): 51 | """`True` if the scanner reached the end of text.""" 52 | return self.pos >= self.data_length 53 | eos = property(eos, eos.__doc__) 54 | 55 | def check(self, pattern): 56 | """ 57 | Apply `pattern` on the current position and return 58 | the match object. (Doesn't touch pos). Use this for 59 | lookahead. 60 | """ 61 | if self.eos: 62 | raise EndOfText() 63 | if pattern not in self._re_cache: 64 | self._re_cache[pattern] = re.compile(pattern, self.flags) 65 | return self._re_cache[pattern].match(self.data, self.pos) 66 | 67 | def test(self, pattern): 68 | """Apply a pattern on the current position and check 69 | if it patches. Doesn't touch pos.""" 70 | return self.check(pattern) is not None 71 | 72 | def scan(self, pattern): 73 | """ 74 | Scan the text for the given pattern and update pos/match 75 | and related fields. The return value is a boolen that 76 | indicates if the pattern matched. The matched value is 77 | stored on the instance as ``match``, the last value is 78 | stored as ``last``. ``start_pos`` is the position of the 79 | pointer before the pattern was matched, ``pos`` is the 80 | end position. 81 | """ 82 | if self.eos: 83 | raise EndOfText() 84 | if pattern not in self._re_cache: 85 | self._re_cache[pattern] = re.compile(pattern, self.flags) 86 | self.last = self.match 87 | m = self._re_cache[pattern].match(self.data, self.pos) 88 | if m is None: 89 | return False 90 | self.start_pos = m.start() 91 | self.pos = m.end() 92 | self.match = m.group() 93 | return True 94 | 95 | def get_char(self): 96 | """Scan exactly one char.""" 97 | self.scan('.') 98 | 99 | def __repr__(self): 100 | return '<%s %d/%d>' % ( 101 | self.__class__.__name__, 102 | self.pos, 103 | self.data_length 104 | ) 105 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/style.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.style 4 | ~~~~~~~~~~~~~~ 5 | 6 | Basic style object. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.token import Token, STANDARD_TYPES 13 | 14 | 15 | class StyleMeta(type): 16 | 17 | def __new__(mcs, name, bases, dct): 18 | obj = type.__new__(mcs, name, bases, dct) 19 | for token in STANDARD_TYPES: 20 | if token not in obj.styles: 21 | obj.styles[token] = '' 22 | 23 | def colorformat(text): 24 | if text[0:1] == '#': 25 | col = text[1:] 26 | if len(col) == 6: 27 | return col 28 | elif len(col) == 3: 29 | return col[0]+'0'+col[1]+'0'+col[2]+'0' 30 | elif text == '': 31 | return '' 32 | assert False, "wrong color format %r" % text 33 | 34 | _styles = obj._styles = {} 35 | 36 | for ttype in obj.styles: 37 | for token in ttype.split(): 38 | if token in _styles: 39 | continue 40 | ndef = _styles.get(token.parent, None) 41 | styledefs = obj.styles.get(token, '').split() 42 | if not ndef or token is None: 43 | ndef = ['', 0, 0, 0, '', '', 0, 0, 0] 44 | elif 'noinherit' in styledefs and token is not Token: 45 | ndef = _styles[Token][:] 46 | else: 47 | ndef = ndef[:] 48 | _styles[token] = ndef 49 | for styledef in obj.styles.get(token, '').split(): 50 | if styledef == 'noinherit': 51 | pass 52 | elif styledef == 'bold': 53 | ndef[1] = 1 54 | elif styledef == 'nobold': 55 | ndef[1] = 0 56 | elif styledef == 'italic': 57 | ndef[2] = 1 58 | elif styledef == 'noitalic': 59 | ndef[2] = 0 60 | elif styledef == 'underline': 61 | ndef[3] = 1 62 | elif styledef == 'nounderline': 63 | ndef[3] = 0 64 | elif styledef[:3] == 'bg:': 65 | ndef[4] = colorformat(styledef[3:]) 66 | elif styledef[:7] == 'border:': 67 | ndef[5] = colorformat(styledef[7:]) 68 | elif styledef == 'roman': 69 | ndef[6] = 1 70 | elif styledef == 'sans': 71 | ndef[7] = 1 72 | elif styledef == 'mono': 73 | ndef[8] = 1 74 | else: 75 | ndef[0] = colorformat(styledef) 76 | 77 | return obj 78 | 79 | def style_for_token(cls, token): 80 | t = cls._styles[token] 81 | return { 82 | 'color': t[0] or None, 83 | 'bold': bool(t[1]), 84 | 'italic': bool(t[2]), 85 | 'underline': bool(t[3]), 86 | 'bgcolor': t[4] or None, 87 | 'border': t[5] or None, 88 | 'roman': bool(t[6]) or None, 89 | 'sans': bool(t[7]) or None, 90 | 'mono': bool(t[8]) or None, 91 | } 92 | 93 | def list_styles(cls): 94 | return list(cls) 95 | 96 | def styles_token(cls, ttype): 97 | return ttype in cls._styles 98 | 99 | def __iter__(cls): 100 | for token in cls._styles: 101 | yield token, cls.style_for_token(token) 102 | 103 | def __len__(cls): 104 | return len(cls._styles) 105 | 106 | 107 | class Style(object): 108 | __metaclass__ = StyleMeta 109 | 110 | #: overall background color (``None`` means transparent) 111 | background_color = '#ffffff' 112 | 113 | #: highlight background color 114 | highlight_color = '#ffffcc' 115 | 116 | #: Style definitions for individual token types. 117 | styles = {} 118 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles 4 | ~~~~~~~~~~~~~~~ 5 | 6 | Contains built-in styles. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.plugin import find_plugin_styles 13 | from pygments.util import ClassNotFound 14 | 15 | 16 | #: Maps style names to 'submodule::classname'. 17 | STYLE_MAP = { 18 | 'default': 'default::DefaultStyle', 19 | 'emacs': 'emacs::EmacsStyle', 20 | 'friendly': 'friendly::FriendlyStyle', 21 | 'colorful': 'colorful::ColorfulStyle', 22 | 'autumn': 'autumn::AutumnStyle', 23 | 'murphy': 'murphy::MurphyStyle', 24 | 'manni': 'manni::ManniStyle', 25 | 'monokai': 'monokai::MonokaiStyle', 26 | 'perldoc': 'perldoc::PerldocStyle', 27 | 'pastie': 'pastie::PastieStyle', 28 | 'borland': 'borland::BorlandStyle', 29 | 'trac': 'trac::TracStyle', 30 | 'native': 'native::NativeStyle', 31 | 'fruity': 'fruity::FruityStyle', 32 | 'bw': 'bw::BlackWhiteStyle', 33 | 'vim': 'vim::VimStyle', 34 | 'vs': 'vs::VisualStudioStyle', 35 | 'tango': 'tango::TangoStyle', 36 | 'rrt': 'rrt::RrtStyle', 37 | } 38 | 39 | 40 | def get_style_by_name(name): 41 | if name in STYLE_MAP: 42 | mod, cls = STYLE_MAP[name].split('::') 43 | builtin = "yes" 44 | else: 45 | for found_name, style in find_plugin_styles(): 46 | if name == found_name: 47 | return style 48 | # perhaps it got dropped into our styles package 49 | builtin = "" 50 | mod = name 51 | cls = name.title() + "Style" 52 | 53 | try: 54 | mod = __import__('pygments.styles.' + mod, None, None, [cls]) 55 | except ImportError: 56 | raise ClassNotFound("Could not find style module %r" % mod + 57 | (builtin and ", though it should be builtin") + ".") 58 | try: 59 | return getattr(mod, cls) 60 | except AttributeError: 61 | raise ClassNotFound("Could not find style class %r in style module." % cls) 62 | 63 | 64 | def get_all_styles(): 65 | """Return an generator for all styles by name, 66 | both builtin and plugin.""" 67 | for name in STYLE_MAP: 68 | yield name 69 | for name, _ in find_plugin_styles(): 70 | yield name 71 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/autumn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.autumn 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A colorful style, inspired by the terminal highlighting style. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class AutumnStyle(Style): 18 | """ 19 | A colorful style, inspired by the terminal highlighting style. 20 | """ 21 | 22 | default_style = "" 23 | 24 | styles = { 25 | Whitespace: '#bbbbbb', 26 | 27 | Comment: 'italic #aaaaaa', 28 | Comment.Preproc: 'noitalic #4c8317', 29 | Comment.Special: 'italic #0000aa', 30 | 31 | Keyword: '#0000aa', 32 | Keyword.Type: '#00aaaa', 33 | 34 | Operator.Word: '#0000aa', 35 | 36 | Name.Builtin: '#00aaaa', 37 | Name.Function: '#00aa00', 38 | Name.Class: 'underline #00aa00', 39 | Name.Namespace: 'underline #00aaaa', 40 | Name.Variable: '#aa0000', 41 | Name.Constant: '#aa0000', 42 | Name.Entity: 'bold #800', 43 | Name.Attribute: '#1e90ff', 44 | Name.Tag: 'bold #1e90ff', 45 | Name.Decorator: '#888888', 46 | 47 | String: '#aa5500', 48 | String.Symbol: '#0000aa', 49 | String.Regex: '#009999', 50 | 51 | Number: '#009999', 52 | 53 | Generic.Heading: 'bold #000080', 54 | Generic.Subheading: 'bold #800080', 55 | Generic.Deleted: '#aa0000', 56 | Generic.Inserted: '#00aa00', 57 | Generic.Error: '#aa0000', 58 | Generic.Emph: 'italic', 59 | Generic.Strong: 'bold', 60 | Generic.Prompt: '#555555', 61 | Generic.Output: '#888888', 62 | Generic.Traceback: '#aa0000', 63 | 64 | Error: '#F00 bg:#FAA' 65 | } 66 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/borland.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.borland 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Style similar to the style used in the Borland IDEs. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class BorlandStyle(Style): 18 | """ 19 | Style similar to the style used in the borland IDEs. 20 | """ 21 | 22 | default_style = '' 23 | 24 | styles = { 25 | Whitespace: '#bbbbbb', 26 | 27 | Comment: 'italic #008800', 28 | Comment.Preproc: 'noitalic #008080', 29 | Comment.Special: 'noitalic bold', 30 | 31 | String: '#0000FF', 32 | String.Char: '#800080', 33 | Number: '#0000FF', 34 | Keyword: 'bold #000080', 35 | Operator.Word: 'bold', 36 | Name.Tag: 'bold #000080', 37 | Name.Attribute: '#FF0000', 38 | 39 | Generic.Heading: '#999999', 40 | Generic.Subheading: '#aaaaaa', 41 | Generic.Deleted: 'bg:#ffdddd #000000', 42 | Generic.Inserted: 'bg:#ddffdd #000000', 43 | Generic.Error: '#aa0000', 44 | Generic.Emph: 'italic', 45 | Generic.Strong: 'bold', 46 | Generic.Prompt: '#555555', 47 | Generic.Output: '#888888', 48 | Generic.Traceback: '#aa0000', 49 | 50 | Error: 'bg:#e3d2d2 #a61717' 51 | } 52 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/bw.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.bw 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Simple black/white only style. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Operator, Generic 15 | 16 | 17 | class BlackWhiteStyle(Style): 18 | 19 | background_color = "#ffffff" 20 | default_style = "" 21 | 22 | styles = { 23 | Comment: "italic", 24 | Comment.Preproc: "noitalic", 25 | 26 | Keyword: "bold", 27 | Keyword.Pseudo: "nobold", 28 | Keyword.Type: "nobold", 29 | 30 | Operator.Word: "bold", 31 | 32 | Name.Class: "bold", 33 | Name.Namespace: "bold", 34 | Name.Exception: "bold", 35 | Name.Entity: "bold", 36 | Name.Tag: "bold", 37 | 38 | String: "italic", 39 | String.Interpol: "bold", 40 | String.Escape: "bold", 41 | 42 | Generic.Heading: "bold", 43 | Generic.Subheading: "bold", 44 | Generic.Emph: "italic", 45 | Generic.Strong: "bold", 46 | Generic.Prompt: "bold", 47 | 48 | Error: "border:#FF0000" 49 | } 50 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/colorful.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.colorful 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A colorful style, inspired by CodeRay. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class ColorfulStyle(Style): 18 | """ 19 | A colorful style, inspired by CodeRay. 20 | """ 21 | 22 | default_style = "" 23 | 24 | styles = { 25 | Whitespace: "#bbbbbb", 26 | 27 | Comment: "#888", 28 | Comment.Preproc: "#579", 29 | Comment.Special: "bold #cc0000", 30 | 31 | Keyword: "bold #080", 32 | Keyword.Pseudo: "#038", 33 | Keyword.Type: "#339", 34 | 35 | Operator: "#333", 36 | Operator.Word: "bold #000", 37 | 38 | Name.Builtin: "#007020", 39 | Name.Function: "bold #06B", 40 | Name.Class: "bold #B06", 41 | Name.Namespace: "bold #0e84b5", 42 | Name.Exception: "bold #F00", 43 | Name.Variable: "#963", 44 | Name.Variable.Instance: "#33B", 45 | Name.Variable.Class: "#369", 46 | Name.Variable.Global: "bold #d70", 47 | Name.Constant: "bold #036", 48 | Name.Label: "bold #970", 49 | Name.Entity: "bold #800", 50 | Name.Attribute: "#00C", 51 | Name.Tag: "#070", 52 | Name.Decorator: "bold #555", 53 | 54 | String: "bg:#fff0f0", 55 | String.Char: "#04D bg:", 56 | String.Doc: "#D42 bg:", 57 | String.Interpol: "bg:#eee", 58 | String.Escape: "bold #666", 59 | String.Regex: "bg:#fff0ff #000", 60 | String.Symbol: "#A60 bg:", 61 | String.Other: "#D20", 62 | 63 | Number: "bold #60E", 64 | Number.Integer: "bold #00D", 65 | Number.Float: "bold #60E", 66 | Number.Hex: "bold #058", 67 | Number.Oct: "bold #40E", 68 | 69 | Generic.Heading: "bold #000080", 70 | Generic.Subheading: "bold #800080", 71 | Generic.Deleted: "#A00000", 72 | Generic.Inserted: "#00A000", 73 | Generic.Error: "#FF0000", 74 | Generic.Emph: "italic", 75 | Generic.Strong: "bold", 76 | Generic.Prompt: "bold #c65d09", 77 | Generic.Output: "#888", 78 | Generic.Traceback: "#04D", 79 | 80 | Error: "#F00 bg:#FAA" 81 | } 82 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/default.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.default 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | The default highlighting style. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class DefaultStyle(Style): 18 | """ 19 | The default style (inspired by Emacs 22). 20 | """ 21 | 22 | background_color = "#f8f8f8" 23 | default_style = "" 24 | 25 | styles = { 26 | Whitespace: "#bbbbbb", 27 | Comment: "italic #408080", 28 | Comment.Preproc: "noitalic #BC7A00", 29 | 30 | #Keyword: "bold #AA22FF", 31 | Keyword: "bold #008000", 32 | Keyword.Pseudo: "nobold", 33 | Keyword.Type: "nobold #B00040", 34 | 35 | Operator: "#666666", 36 | Operator.Word: "bold #AA22FF", 37 | 38 | Name.Builtin: "#008000", 39 | Name.Function: "#0000FF", 40 | Name.Class: "bold #0000FF", 41 | Name.Namespace: "bold #0000FF", 42 | Name.Exception: "bold #D2413A", 43 | Name.Variable: "#19177C", 44 | Name.Constant: "#880000", 45 | Name.Label: "#A0A000", 46 | Name.Entity: "bold #999999", 47 | Name.Attribute: "#7D9029", 48 | Name.Tag: "bold #008000", 49 | Name.Decorator: "#AA22FF", 50 | 51 | String: "#BA2121", 52 | String.Doc: "italic", 53 | String.Interpol: "bold #BB6688", 54 | String.Escape: "bold #BB6622", 55 | String.Regex: "#BB6688", 56 | #String.Symbol: "#B8860B", 57 | String.Symbol: "#19177C", 58 | String.Other: "#008000", 59 | Number: "#666666", 60 | 61 | Generic.Heading: "bold #000080", 62 | Generic.Subheading: "bold #800080", 63 | Generic.Deleted: "#A00000", 64 | Generic.Inserted: "#00A000", 65 | Generic.Error: "#FF0000", 66 | Generic.Emph: "italic", 67 | Generic.Strong: "bold", 68 | Generic.Prompt: "bold #000080", 69 | Generic.Output: "#888", 70 | Generic.Traceback: "#04D", 71 | 72 | Error: "border:#FF0000" 73 | } 74 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/emacs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.emacs 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A highlighting style for Pygments, inspired by Emacs. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class EmacsStyle(Style): 18 | """ 19 | The default style (inspired by Emacs 22). 20 | """ 21 | 22 | background_color = "#f8f8f8" 23 | default_style = "" 24 | 25 | styles = { 26 | Whitespace: "#bbbbbb", 27 | Comment: "italic #008800", 28 | Comment.Preproc: "noitalic", 29 | Comment.Special: "noitalic bold", 30 | 31 | Keyword: "bold #AA22FF", 32 | Keyword.Pseudo: "nobold", 33 | Keyword.Type: "bold #00BB00", 34 | 35 | Operator: "#666666", 36 | Operator.Word: "bold #AA22FF", 37 | 38 | Name.Builtin: "#AA22FF", 39 | Name.Function: "#00A000", 40 | Name.Class: "#0000FF", 41 | Name.Namespace: "bold #0000FF", 42 | Name.Exception: "bold #D2413A", 43 | Name.Variable: "#B8860B", 44 | Name.Constant: "#880000", 45 | Name.Label: "#A0A000", 46 | Name.Entity: "bold #999999", 47 | Name.Attribute: "#BB4444", 48 | Name.Tag: "bold #008000", 49 | Name.Decorator: "#AA22FF", 50 | 51 | String: "#BB4444", 52 | String.Doc: "italic", 53 | String.Interpol: "bold #BB6688", 54 | String.Escape: "bold #BB6622", 55 | String.Regex: "#BB6688", 56 | String.Symbol: "#B8860B", 57 | String.Other: "#008000", 58 | Number: "#666666", 59 | 60 | Generic.Heading: "bold #000080", 61 | Generic.Subheading: "bold #800080", 62 | Generic.Deleted: "#A00000", 63 | Generic.Inserted: "#00A000", 64 | Generic.Error: "#FF0000", 65 | Generic.Emph: "italic", 66 | Generic.Strong: "bold", 67 | Generic.Prompt: "bold #000080", 68 | Generic.Output: "#888", 69 | Generic.Traceback: "#04D", 70 | 71 | Error: "border:#FF0000" 72 | } 73 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/friendly.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.friendly 4 | ~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A modern style based on the VIM pyte theme. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class FriendlyStyle(Style): 18 | """ 19 | A modern style based on the VIM pyte theme. 20 | """ 21 | 22 | background_color = "#f0f0f0" 23 | default_style = "" 24 | 25 | styles = { 26 | Whitespace: "#bbbbbb", 27 | Comment: "italic #60a0b0", 28 | Comment.Preproc: "noitalic #007020", 29 | Comment.Special: "noitalic bg:#fff0f0", 30 | 31 | Keyword: "bold #007020", 32 | Keyword.Pseudo: "nobold", 33 | Keyword.Type: "nobold #902000", 34 | 35 | Operator: "#666666", 36 | Operator.Word: "bold #007020", 37 | 38 | Name.Builtin: "#007020", 39 | Name.Function: "#06287e", 40 | Name.Class: "bold #0e84b5", 41 | Name.Namespace: "bold #0e84b5", 42 | Name.Exception: "#007020", 43 | Name.Variable: "#bb60d5", 44 | Name.Constant: "#60add5", 45 | Name.Label: "bold #002070", 46 | Name.Entity: "bold #d55537", 47 | Name.Attribute: "#4070a0", 48 | Name.Tag: "bold #062873", 49 | Name.Decorator: "bold #555555", 50 | 51 | String: "#4070a0", 52 | String.Doc: "italic", 53 | String.Interpol: "italic #70a0d0", 54 | String.Escape: "bold #4070a0", 55 | String.Regex: "#235388", 56 | String.Symbol: "#517918", 57 | String.Other: "#c65d09", 58 | Number: "#40a070", 59 | 60 | Generic.Heading: "bold #000080", 61 | Generic.Subheading: "bold #800080", 62 | Generic.Deleted: "#A00000", 63 | Generic.Inserted: "#00A000", 64 | Generic.Error: "#FF0000", 65 | Generic.Emph: "italic", 66 | Generic.Strong: "bold", 67 | Generic.Prompt: "bold #c65d09", 68 | Generic.Output: "#888", 69 | Generic.Traceback: "#04D", 70 | 71 | Error: "border:#FF0000" 72 | } 73 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/fruity.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.fruity 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | pygments version of my "fruity" vim theme. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Token, Comment, Name, Keyword, \ 14 | Generic, Number, String, Whitespace 15 | 16 | class FruityStyle(Style): 17 | """ 18 | Pygments version of the "native" vim theme. 19 | """ 20 | 21 | background_color = '#111111' 22 | highlight_color = '#333333' 23 | 24 | styles = { 25 | Whitespace: '#888888', 26 | Token: '#ffffff', 27 | Generic.Output: '#444444 bg:#222222', 28 | Keyword: '#fb660a bold', 29 | Keyword.Pseudo: 'nobold', 30 | Number: '#0086f7 bold', 31 | Name.Tag: '#fb660a bold', 32 | Name.Variable: '#fb660a', 33 | Comment: '#008800 bg:#0f140f italic', 34 | Name.Attribute: '#ff0086 bold', 35 | String: '#0086d2', 36 | Name.Function: '#ff0086 bold', 37 | Generic.Heading: '#ffffff bold', 38 | Keyword.Type: '#cdcaa9 bold', 39 | Generic.Subheading: '#ffffff bold', 40 | Name.Constant: '#0086d2', 41 | Comment.Preproc: '#ff0007 bold' 42 | } 43 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/manni.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.manni 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | A colorful style, inspired by the terminal highlighting style. 7 | 8 | This is a port of the style used in the `php port`_ of pygments 9 | by Manni. The style is called 'default' there. 10 | 11 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 12 | :license: BSD, see LICENSE for details. 13 | """ 14 | 15 | from pygments.style import Style 16 | from pygments.token import Keyword, Name, Comment, String, Error, \ 17 | Number, Operator, Generic, Whitespace 18 | 19 | 20 | class ManniStyle(Style): 21 | """ 22 | A colorful style, inspired by the terminal highlighting style. 23 | """ 24 | 25 | background_color = '#f0f3f3' 26 | 27 | styles = { 28 | Whitespace: '#bbbbbb', 29 | Comment: 'italic #0099FF', 30 | Comment.Preproc: 'noitalic #009999', 31 | Comment.Special: 'bold', 32 | 33 | Keyword: 'bold #006699', 34 | Keyword.Pseudo: 'nobold', 35 | Keyword.Type: '#007788', 36 | 37 | Operator: '#555555', 38 | Operator.Word: 'bold #000000', 39 | 40 | Name.Builtin: '#336666', 41 | Name.Function: '#CC00FF', 42 | Name.Class: 'bold #00AA88', 43 | Name.Namespace: 'bold #00CCFF', 44 | Name.Exception: 'bold #CC0000', 45 | Name.Variable: '#003333', 46 | Name.Constant: '#336600', 47 | Name.Label: '#9999FF', 48 | Name.Entity: 'bold #999999', 49 | Name.Attribute: '#330099', 50 | Name.Tag: 'bold #330099', 51 | Name.Decorator: '#9999FF', 52 | 53 | String: '#CC3300', 54 | String.Doc: 'italic', 55 | String.Interpol: '#AA0000', 56 | String.Escape: 'bold #CC3300', 57 | String.Regex: '#33AAAA', 58 | String.Symbol: '#FFCC33', 59 | String.Other: '#CC3300', 60 | 61 | Number: '#FF6600', 62 | 63 | Generic.Heading: 'bold #003300', 64 | Generic.Subheading: 'bold #003300', 65 | Generic.Deleted: 'border:#CC0000 bg:#FFCCCC', 66 | Generic.Inserted: 'border:#00CC00 bg:#CCFFCC', 67 | Generic.Error: '#FF0000', 68 | Generic.Emph: 'italic', 69 | Generic.Strong: 'bold', 70 | Generic.Prompt: 'bold #000099', 71 | Generic.Output: '#AAAAAA', 72 | Generic.Traceback: '#99CC66', 73 | 74 | Error: 'bg:#FFAAAA #AA0000' 75 | } 76 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/monokai.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.monokai 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Mimic the Monokai color scheme. Based on tango.py. 7 | 8 | http://www.monokai.nl/blog/2006/07/15/textmate-color-theme/ 9 | 10 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 11 | :license: BSD, see LICENSE for details. 12 | """ 13 | 14 | from pygments.style import Style 15 | from pygments.token import Keyword, Name, Comment, String, Error, Text, \ 16 | Number, Operator, Generic, Whitespace, Punctuation, Other, Literal 17 | 18 | class MonokaiStyle(Style): 19 | """ 20 | This style mimics the Monokai color scheme. 21 | """ 22 | 23 | background_color = "#272822" 24 | highlight_color = "#49483e" 25 | 26 | styles = { 27 | # No corresponding class for the following: 28 | Text: "#f8f8f2", # class: '' 29 | Whitespace: "", # class: 'w' 30 | Error: "#960050 bg:#1e0010", # class: 'err' 31 | Other: "", # class 'x' 32 | 33 | Comment: "#75715e", # class: 'c' 34 | Comment.Multiline: "", # class: 'cm' 35 | Comment.Preproc: "", # class: 'cp' 36 | Comment.Single: "", # class: 'c1' 37 | Comment.Special: "", # class: 'cs' 38 | 39 | Keyword: "#66d9ef", # class: 'k' 40 | Keyword.Constant: "", # class: 'kc' 41 | Keyword.Declaration: "", # class: 'kd' 42 | Keyword.Namespace: "#f92672", # class: 'kn' 43 | Keyword.Pseudo: "", # class: 'kp' 44 | Keyword.Reserved: "", # class: 'kr' 45 | Keyword.Type: "", # class: 'kt' 46 | 47 | Operator: "#f92672", # class: 'o' 48 | Operator.Word: "", # class: 'ow' - like keywords 49 | 50 | Punctuation: "#f8f8f2", # class: 'p' 51 | 52 | Name: "#f8f8f2", # class: 'n' 53 | Name.Attribute: "#a6e22e", # class: 'na' - to be revised 54 | Name.Builtin: "", # class: 'nb' 55 | Name.Builtin.Pseudo: "", # class: 'bp' 56 | Name.Class: "#a6e22e", # class: 'nc' - to be revised 57 | Name.Constant: "#66d9ef", # class: 'no' - to be revised 58 | Name.Decorator: "#a6e22e", # class: 'nd' - to be revised 59 | Name.Entity: "", # class: 'ni' 60 | Name.Exception: "#a6e22e", # class: 'ne' 61 | Name.Function: "#a6e22e", # class: 'nf' 62 | Name.Property: "", # class: 'py' 63 | Name.Label: "", # class: 'nl' 64 | Name.Namespace: "", # class: 'nn' - to be revised 65 | Name.Other: "#a6e22e", # class: 'nx' 66 | Name.Tag: "#f92672", # class: 'nt' - like a keyword 67 | Name.Variable: "", # class: 'nv' - to be revised 68 | Name.Variable.Class: "", # class: 'vc' - to be revised 69 | Name.Variable.Global: "", # class: 'vg' - to be revised 70 | Name.Variable.Instance: "", # class: 'vi' - to be revised 71 | 72 | Number: "#ae81ff", # class: 'm' 73 | Number.Float: "", # class: 'mf' 74 | Number.Hex: "", # class: 'mh' 75 | Number.Integer: "", # class: 'mi' 76 | Number.Integer.Long: "", # class: 'il' 77 | Number.Oct: "", # class: 'mo' 78 | 79 | Literal: "#ae81ff", # class: 'l' 80 | Literal.Date: "#e6db74", # class: 'ld' 81 | 82 | String: "#e6db74", # class: 's' 83 | String.Backtick: "", # class: 'sb' 84 | String.Char: "", # class: 'sc' 85 | String.Doc: "", # class: 'sd' - like a comment 86 | String.Double: "", # class: 's2' 87 | String.Escape: "#ae81ff", # class: 'se' 88 | String.Heredoc: "", # class: 'sh' 89 | String.Interpol: "", # class: 'si' 90 | String.Other: "", # class: 'sx' 91 | String.Regex: "", # class: 'sr' 92 | String.Single: "", # class: 's1' 93 | String.Symbol: "", # class: 'ss' 94 | 95 | Generic: "", # class: 'g' 96 | Generic.Deleted: "", # class: 'gd', 97 | Generic.Emph: "italic", # class: 'ge' 98 | Generic.Error: "", # class: 'gr' 99 | Generic.Heading: "", # class: 'gh' 100 | Generic.Inserted: "", # class: 'gi' 101 | Generic.Output: "", # class: 'go' 102 | Generic.Prompt: "", # class: 'gp' 103 | Generic.Strong: "bold", # class: 'gs' 104 | Generic.Subheading: "", # class: 'gu' 105 | Generic.Traceback: "", # class: 'gt' 106 | } 107 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/murphy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.murphy 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Murphy's style from CodeRay. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class MurphyStyle(Style): 18 | """ 19 | Murphy's style from CodeRay. 20 | """ 21 | 22 | default_style = "" 23 | 24 | styles = { 25 | Whitespace: "#bbbbbb", 26 | Comment: "#666 italic", 27 | Comment.Preproc: "#579 noitalic", 28 | Comment.Special: "#c00 bold", 29 | 30 | Keyword: "bold #289", 31 | Keyword.Pseudo: "#08f", 32 | Keyword.Type: "#66f", 33 | 34 | Operator: "#333", 35 | Operator.Word: "bold #000", 36 | 37 | Name.Builtin: "#072", 38 | Name.Function: "bold #5ed", 39 | Name.Class: "bold #e9e", 40 | Name.Namespace: "bold #0e84b5", 41 | Name.Exception: "bold #F00", 42 | Name.Variable: "#036", 43 | Name.Variable.Instance: "#aaf", 44 | Name.Variable.Class: "#ccf", 45 | Name.Variable.Global: "#f84", 46 | Name.Constant: "bold #5ed", 47 | Name.Label: "bold #970", 48 | Name.Entity: "#800", 49 | Name.Attribute: "#007", 50 | Name.Tag: "#070", 51 | Name.Decorator: "bold #555", 52 | 53 | String: "bg:#e0e0ff", 54 | String.Char: "#88F bg:", 55 | String.Doc: "#D42 bg:", 56 | String.Interpol: "bg:#eee", 57 | String.Escape: "bold #666", 58 | String.Regex: "bg:#e0e0ff #000", 59 | String.Symbol: "#fc8 bg:", 60 | String.Other: "#f88", 61 | 62 | Number: "bold #60E", 63 | Number.Integer: "bold #66f", 64 | Number.Float: "bold #60E", 65 | Number.Hex: "bold #058", 66 | Number.Oct: "bold #40E", 67 | 68 | Generic.Heading: "bold #000080", 69 | Generic.Subheading: "bold #800080", 70 | Generic.Deleted: "#A00000", 71 | Generic.Inserted: "#00A000", 72 | Generic.Error: "#FF0000", 73 | Generic.Emph: "italic", 74 | Generic.Strong: "bold", 75 | Generic.Prompt: "bold #c65d09", 76 | Generic.Output: "#888", 77 | Generic.Traceback: "#04D", 78 | 79 | Error: "#F00 bg:#FAA" 80 | } 81 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/native.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.native 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | pygments version of my "native" vim theme. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Token, Whitespace 15 | 16 | 17 | class NativeStyle(Style): 18 | """ 19 | Pygments version of the "native" vim theme. 20 | """ 21 | 22 | background_color = '#202020' 23 | highlight_color = '#404040' 24 | 25 | styles = { 26 | Token: '#d0d0d0', 27 | Whitespace: '#666666', 28 | 29 | Comment: 'italic #999999', 30 | Comment.Preproc: 'noitalic bold #cd2828', 31 | Comment.Special: 'noitalic bold #e50808 bg:#520000', 32 | 33 | Keyword: 'bold #6ab825', 34 | Keyword.Pseudo: 'nobold', 35 | Operator.Word: 'bold #6ab825', 36 | 37 | String: '#ed9d13', 38 | String.Other: '#ffa500', 39 | 40 | Number: '#3677a9', 41 | 42 | Name.Builtin: '#24909d', 43 | Name.Variable: '#40ffff', 44 | Name.Constant: '#40ffff', 45 | Name.Class: 'underline #447fcf', 46 | Name.Function: '#447fcf', 47 | Name.Namespace: 'underline #447fcf', 48 | Name.Exception: '#bbbbbb', 49 | Name.Tag: 'bold #6ab825', 50 | Name.Attribute: '#bbbbbb', 51 | Name.Decorator: '#ffa500', 52 | 53 | Generic.Heading: 'bold #ffffff', 54 | Generic.Subheading: 'underline #ffffff', 55 | Generic.Deleted: '#d22323', 56 | Generic.Inserted: '#589819', 57 | Generic.Error: '#d22323', 58 | Generic.Emph: 'italic', 59 | Generic.Strong: 'bold', 60 | Generic.Prompt: '#aaaaaa', 61 | Generic.Output: '#cccccc', 62 | Generic.Traceback: '#d22323', 63 | 64 | Error: 'bg:#e3d2d2 #a61717' 65 | } 66 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/pastie.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.pastie 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Style similar to the `pastie`_ default style. 7 | 8 | .. _pastie: http://pastie.caboo.se/ 9 | 10 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 11 | :license: BSD, see LICENSE for details. 12 | """ 13 | 14 | from pygments.style import Style 15 | from pygments.token import Keyword, Name, Comment, String, Error, \ 16 | Number, Operator, Generic, Whitespace 17 | 18 | 19 | class PastieStyle(Style): 20 | """ 21 | Style similar to the pastie default style. 22 | """ 23 | 24 | default_style = '' 25 | 26 | styles = { 27 | Whitespace: '#bbbbbb', 28 | Comment: '#888888', 29 | Comment.Preproc: 'bold #cc0000', 30 | Comment.Special: 'bg:#fff0f0 bold #cc0000', 31 | 32 | String: 'bg:#fff0f0 #dd2200', 33 | String.Regex: 'bg:#fff0ff #008800', 34 | String.Other: 'bg:#f0fff0 #22bb22', 35 | String.Symbol: '#aa6600', 36 | String.Interpol: '#3333bb', 37 | String.Escape: '#0044dd', 38 | 39 | Operator.Word: '#008800', 40 | 41 | Keyword: 'bold #008800', 42 | Keyword.Pseudo: 'nobold', 43 | Keyword.Type: '#888888', 44 | 45 | Name.Class: 'bold #bb0066', 46 | Name.Exception: 'bold #bb0066', 47 | Name.Function: 'bold #0066bb', 48 | Name.Property: 'bold #336699', 49 | Name.Namespace: 'bold #bb0066', 50 | Name.Builtin: '#003388', 51 | Name.Variable: '#336699', 52 | Name.Variable.Class: '#336699', 53 | Name.Variable.Instance: '#3333bb', 54 | Name.Variable.Global: '#dd7700', 55 | Name.Constant: 'bold #003366', 56 | Name.Tag: 'bold #bb0066', 57 | Name.Attribute: '#336699', 58 | Name.Decorator: '#555555', 59 | Name.Label: 'italic #336699', 60 | 61 | Number: 'bold #0000DD', 62 | 63 | Generic.Heading: '#333', 64 | Generic.Subheading: '#666', 65 | Generic.Deleted: 'bg:#ffdddd #000000', 66 | Generic.Inserted: 'bg:#ddffdd #000000', 67 | Generic.Error: '#aa0000', 68 | Generic.Emph: 'italic', 69 | Generic.Strong: 'bold', 70 | Generic.Prompt: '#555555', 71 | Generic.Output: '#888888', 72 | Generic.Traceback: '#aa0000', 73 | 74 | Error: 'bg:#e3d2d2 #a61717' 75 | } 76 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/perldoc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.perldoc 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Style similar to the style used in the `perldoc`_ code blocks. 7 | 8 | .. _perldoc: http://perldoc.perl.org/ 9 | 10 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 11 | :license: BSD, see LICENSE for details. 12 | """ 13 | 14 | from pygments.style import Style 15 | from pygments.token import Keyword, Name, Comment, String, Error, \ 16 | Number, Operator, Generic, Whitespace 17 | 18 | 19 | class PerldocStyle(Style): 20 | """ 21 | Style similar to the style used in the perldoc code blocks. 22 | """ 23 | 24 | background_color = '#eeeedd' 25 | default_style = '' 26 | 27 | styles = { 28 | Whitespace: '#bbbbbb', 29 | Comment: '#228B22', 30 | Comment.Preproc: '#1e889b', 31 | Comment.Special: '#8B008B bold', 32 | 33 | String: '#CD5555', 34 | String.Heredoc: '#1c7e71 italic', 35 | String.Regex: '#B452CD', 36 | String.Other: '#cb6c20', 37 | String.Regex: '#1c7e71', 38 | 39 | Number: '#B452CD', 40 | 41 | Operator.Word: '#8B008B', 42 | 43 | Keyword: '#8B008B bold', 44 | Keyword.Type: '#a7a7a7', 45 | 46 | Name.Class: '#008b45 bold', 47 | Name.Exception: '#008b45 bold', 48 | Name.Function: '#008b45', 49 | Name.Namespace: '#008b45 underline', 50 | Name.Variable: '#00688B', 51 | Name.Constant: '#00688B', 52 | Name.Decorator: '#707a7c', 53 | Name.Tag: '#8B008B bold', 54 | Name.Attribute: '#658b00', 55 | Name.Builtin: '#658b00', 56 | 57 | Generic.Heading: 'bold #000080', 58 | Generic.Subheading: 'bold #800080', 59 | Generic.Deleted: '#aa0000', 60 | Generic.Inserted: '#00aa00', 61 | Generic.Error: '#aa0000', 62 | Generic.Emph: 'italic', 63 | Generic.Strong: 'bold', 64 | Generic.Prompt: '#555555', 65 | Generic.Output: '#888888', 66 | Generic.Traceback: '#aa0000', 67 | 68 | Error: 'bg:#e3d2d2 #a61717' 69 | } 70 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/rrt.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.rrt 4 | ~~~~~~~~~~~~~~~~~~~ 5 | 6 | pygments "rrt" theme, based on Zap and Emacs defaults. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Comment, Name, Keyword, String 14 | 15 | 16 | class RrtStyle(Style): 17 | """ 18 | Minimalistic "rrt" theme, based on Zap and Emacs defaults. 19 | """ 20 | 21 | background_color = '#000000' 22 | highlight_color = '#0000ff' 23 | 24 | styles = { 25 | Comment: '#00ff00', 26 | Name.Function: '#ffff00', 27 | Name.Variable: '#eedd82', 28 | Name.Constant: '#7fffd4', 29 | Keyword: '#ff0000', 30 | Comment.Preproc: '#e5e5e5', 31 | String: '#87ceeb', 32 | Keyword.Type: '#ee82ee', 33 | } 34 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/tango.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.tango 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | The Crunchy default Style inspired from the color palette from 7 | the Tango Icon Theme Guidelines. 8 | 9 | http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines 10 | 11 | Butter: #fce94f #edd400 #c4a000 12 | Orange: #fcaf3e #f57900 #ce5c00 13 | Chocolate: #e9b96e #c17d11 #8f5902 14 | Chameleon: #8ae234 #73d216 #4e9a06 15 | Sky Blue: #729fcf #3465a4 #204a87 16 | Plum: #ad7fa8 #75507b #5c35cc 17 | Scarlet Red:#ef2929 #cc0000 #a40000 18 | Aluminium: #eeeeec #d3d7cf #babdb6 19 | #888a85 #555753 #2e3436 20 | 21 | Not all of the above colors are used; other colors added: 22 | very light grey: #f8f8f8 (for background) 23 | 24 | This style can be used as a template as it includes all the known 25 | Token types, unlike most (if not all) of the styles included in the 26 | Pygments distribution. 27 | 28 | However, since Crunchy is intended to be used by beginners, we have strived 29 | to create a style that gloss over subtle distinctions between different 30 | categories. 31 | 32 | Taking Python for example, comments (Comment.*) and docstrings (String.Doc) 33 | have been chosen to have the same style. Similarly, keywords (Keyword.*), 34 | and Operator.Word (and, or, in) have been assigned the same style. 35 | 36 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 37 | :license: BSD, see LICENSE for details. 38 | """ 39 | 40 | from pygments.style import Style 41 | from pygments.token import Keyword, Name, Comment, String, Error, \ 42 | Number, Operator, Generic, Whitespace, Punctuation, Other, Literal 43 | 44 | 45 | class TangoStyle(Style): 46 | """ 47 | The Crunchy default Style inspired from the color palette from 48 | the Tango Icon Theme Guidelines. 49 | """ 50 | 51 | # work in progress... 52 | 53 | background_color = "#f8f8f8" 54 | default_style = "" 55 | 56 | styles = { 57 | # No corresponding class for the following: 58 | #Text: "", # class: '' 59 | Whitespace: "underline #f8f8f8", # class: 'w' 60 | Error: "#a40000 border:#ef2929", # class: 'err' 61 | Other: "#000000", # class 'x' 62 | 63 | Comment: "italic #8f5902", # class: 'c' 64 | Comment.Multiline: "italic #8f5902", # class: 'cm' 65 | Comment.Preproc: "italic #8f5902", # class: 'cp' 66 | Comment.Single: "italic #8f5902", # class: 'c1' 67 | Comment.Special: "italic #8f5902", # class: 'cs' 68 | 69 | Keyword: "bold #204a87", # class: 'k' 70 | Keyword.Constant: "bold #204a87", # class: 'kc' 71 | Keyword.Declaration: "bold #204a87", # class: 'kd' 72 | Keyword.Namespace: "bold #204a87", # class: 'kn' 73 | Keyword.Pseudo: "bold #204a87", # class: 'kp' 74 | Keyword.Reserved: "bold #204a87", # class: 'kr' 75 | Keyword.Type: "bold #204a87", # class: 'kt' 76 | 77 | Operator: "bold #ce5c00", # class: 'o' 78 | Operator.Word: "bold #204a87", # class: 'ow' - like keywords 79 | 80 | Punctuation: "bold #000000", # class: 'p' 81 | 82 | # because special names such as Name.Class, Name.Function, etc. 83 | # are not recognized as such later in the parsing, we choose them 84 | # to look the same as ordinary variables. 85 | Name: "#000000", # class: 'n' 86 | Name.Attribute: "#c4a000", # class: 'na' - to be revised 87 | Name.Builtin: "#204a87", # class: 'nb' 88 | Name.Builtin.Pseudo: "#3465a4", # class: 'bp' 89 | Name.Class: "#000000", # class: 'nc' - to be revised 90 | Name.Constant: "#000000", # class: 'no' - to be revised 91 | Name.Decorator: "bold #5c35cc", # class: 'nd' - to be revised 92 | Name.Entity: "#ce5c00", # class: 'ni' 93 | Name.Exception: "bold #cc0000", # class: 'ne' 94 | Name.Function: "#000000", # class: 'nf' 95 | Name.Property: "#000000", # class: 'py' 96 | Name.Label: "#f57900", # class: 'nl' 97 | Name.Namespace: "#000000", # class: 'nn' - to be revised 98 | Name.Other: "#000000", # class: 'nx' 99 | Name.Tag: "bold #204a87", # class: 'nt' - like a keyword 100 | Name.Variable: "#000000", # class: 'nv' - to be revised 101 | Name.Variable.Class: "#000000", # class: 'vc' - to be revised 102 | Name.Variable.Global: "#000000", # class: 'vg' - to be revised 103 | Name.Variable.Instance: "#000000", # class: 'vi' - to be revised 104 | 105 | # since the tango light blue does not show up well in text, we choose 106 | # a pure blue instead. 107 | Number: "bold #0000cf", # class: 'm' 108 | Number.Float: "bold #0000cf", # class: 'mf' 109 | Number.Hex: "bold #0000cf", # class: 'mh' 110 | Number.Integer: "bold #0000cf", # class: 'mi' 111 | Number.Integer.Long: "bold #0000cf", # class: 'il' 112 | Number.Oct: "bold #0000cf", # class: 'mo' 113 | 114 | Literal: "#000000", # class: 'l' 115 | Literal.Date: "#000000", # class: 'ld' 116 | 117 | String: "#4e9a06", # class: 's' 118 | String.Backtick: "#4e9a06", # class: 'sb' 119 | String.Char: "#4e9a06", # class: 'sc' 120 | String.Doc: "italic #8f5902", # class: 'sd' - like a comment 121 | String.Double: "#4e9a06", # class: 's2' 122 | String.Escape: "#4e9a06", # class: 'se' 123 | String.Heredoc: "#4e9a06", # class: 'sh' 124 | String.Interpol: "#4e9a06", # class: 'si' 125 | String.Other: "#4e9a06", # class: 'sx' 126 | String.Regex: "#4e9a06", # class: 'sr' 127 | String.Single: "#4e9a06", # class: 's1' 128 | String.Symbol: "#4e9a06", # class: 'ss' 129 | 130 | Generic: "#000000", # class: 'g' 131 | Generic.Deleted: "#a40000", # class: 'gd' 132 | Generic.Emph: "italic #000000", # class: 'ge' 133 | Generic.Error: "#ef2929", # class: 'gr' 134 | Generic.Heading: "bold #000080", # class: 'gh' 135 | Generic.Inserted: "#00A000", # class: 'gi' 136 | Generic.Output: "italic #000000", # class: 'go' 137 | Generic.Prompt: "#8f5902", # class: 'gp' 138 | Generic.Strong: "bold #000000", # class: 'gs' 139 | Generic.Subheading: "bold #800080", # class: 'gu' 140 | Generic.Traceback: "bold #a40000", # class: 'gt' 141 | } 142 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/trac.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.trac 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Port of the default trac highlighter design. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace 15 | 16 | 17 | class TracStyle(Style): 18 | """ 19 | Port of the default trac highlighter design. 20 | """ 21 | 22 | default_style = '' 23 | 24 | styles = { 25 | Whitespace: '#bbbbbb', 26 | Comment: 'italic #999988', 27 | Comment.Preproc: 'bold noitalic #999999', 28 | Comment.Special: 'bold #999999', 29 | 30 | Operator: 'bold', 31 | 32 | String: '#bb8844', 33 | String.Regex: '#808000', 34 | 35 | Number: '#009999', 36 | 37 | Keyword: 'bold', 38 | Keyword.Type: '#445588', 39 | 40 | Name.Builtin: '#999999', 41 | Name.Function: 'bold #990000', 42 | Name.Class: 'bold #445588', 43 | Name.Exception: 'bold #990000', 44 | Name.Namespace: '#555555', 45 | Name.Variable: '#008080', 46 | Name.Constant: '#008080', 47 | Name.Tag: '#000080', 48 | Name.Attribute: '#008080', 49 | Name.Entity: '#800080', 50 | 51 | Generic.Heading: '#999999', 52 | Generic.Subheading: '#aaaaaa', 53 | Generic.Deleted: 'bg:#ffdddd #000000', 54 | Generic.Inserted: 'bg:#ddffdd #000000', 55 | Generic.Error: '#aa0000', 56 | Generic.Emph: 'italic', 57 | Generic.Strong: 'bold', 58 | Generic.Prompt: '#555555', 59 | Generic.Output: '#888888', 60 | Generic.Traceback: '#aa0000', 61 | 62 | Error: 'bg:#e3d2d2 #a61717' 63 | } 64 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/vim.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.vim 4 | ~~~~~~~~~~~~~~~~~~~ 5 | 6 | A highlighting style for Pygments, inspired by vim. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Number, Operator, Generic, Whitespace, Token 15 | 16 | 17 | class VimStyle(Style): 18 | """ 19 | Styles somewhat like vim 7.0 20 | """ 21 | 22 | background_color = "#000000" 23 | highlight_color = "#222222" 24 | default_style = "#cccccc" 25 | 26 | styles = { 27 | Token: "#cccccc", 28 | Whitespace: "", 29 | Comment: "#000080", 30 | Comment.Preproc: "", 31 | Comment.Special: "bold #cd0000", 32 | 33 | Keyword: "#cdcd00", 34 | Keyword.Declaration: "#00cd00", 35 | Keyword.Namespace: "#cd00cd", 36 | Keyword.Pseudo: "", 37 | Keyword.Type: "#00cd00", 38 | 39 | Operator: "#3399cc", 40 | Operator.Word: "#cdcd00", 41 | 42 | Name: "", 43 | Name.Class: "#00cdcd", 44 | Name.Builtin: "#cd00cd", 45 | Name.Exception: "bold #666699", 46 | Name.Variable: "#00cdcd", 47 | 48 | String: "#cd0000", 49 | Number: "#cd00cd", 50 | 51 | Generic.Heading: "bold #000080", 52 | Generic.Subheading: "bold #800080", 53 | Generic.Deleted: "#cd0000", 54 | Generic.Inserted: "#00cd00", 55 | Generic.Error: "#FF0000", 56 | Generic.Emph: "italic", 57 | Generic.Strong: "bold", 58 | Generic.Prompt: "bold #000080", 59 | Generic.Output: "#888", 60 | Generic.Traceback: "#04D", 61 | 62 | Error: "border:#FF0000" 63 | } 64 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/styles/vs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.styles.vs 4 | ~~~~~~~~~~~~~~~~~~ 5 | 6 | Simple style with MS Visual Studio colors. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | from pygments.style import Style 13 | from pygments.token import Keyword, Name, Comment, String, Error, \ 14 | Operator, Generic 15 | 16 | 17 | class VisualStudioStyle(Style): 18 | 19 | background_color = "#ffffff" 20 | default_style = "" 21 | 22 | styles = { 23 | Comment: "#008000", 24 | Comment.Preproc: "#0000ff", 25 | Keyword: "#0000ff", 26 | Operator.Word: "#0000ff", 27 | Keyword.Type: "#2b91af", 28 | Name.Class: "#2b91af", 29 | String: "#a31515", 30 | 31 | Generic.Heading: "bold", 32 | Generic.Subheading: "bold", 33 | Generic.Emph: "italic", 34 | Generic.Strong: "bold", 35 | Generic.Prompt: "bold", 36 | 37 | Error: "border:#FF0000" 38 | } 39 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/token.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.token 4 | ~~~~~~~~~~~~~~ 5 | 6 | Basic token types and the standard tokens. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | class _TokenType(tuple): 13 | parent = None 14 | 15 | def split(self): 16 | buf = [] 17 | node = self 18 | while node is not None: 19 | buf.append(node) 20 | node = node.parent 21 | buf.reverse() 22 | return buf 23 | 24 | def __init__(self, *args): 25 | # no need to call super.__init__ 26 | self.subtypes = set() 27 | 28 | def __contains__(self, val): 29 | return self is val or ( 30 | type(val) is self.__class__ and 31 | val[:len(self)] == self 32 | ) 33 | 34 | def __getattr__(self, val): 35 | if not val or not val[0].isupper(): 36 | return tuple.__getattribute__(self, val) 37 | new = _TokenType(self + (val,)) 38 | setattr(self, val, new) 39 | self.subtypes.add(new) 40 | new.parent = self 41 | return new 42 | 43 | def __repr__(self): 44 | return 'Token' + (self and '.' or '') + '.'.join(self) 45 | 46 | 47 | Token = _TokenType() 48 | 49 | # Special token types 50 | Text = Token.Text 51 | Whitespace = Text.Whitespace 52 | Error = Token.Error 53 | # Text that doesn't belong to this lexer (e.g. HTML in PHP) 54 | Other = Token.Other 55 | 56 | # Common token types for source code 57 | Keyword = Token.Keyword 58 | Name = Token.Name 59 | Literal = Token.Literal 60 | String = Literal.String 61 | Number = Literal.Number 62 | Punctuation = Token.Punctuation 63 | Operator = Token.Operator 64 | Comment = Token.Comment 65 | 66 | # Generic types for non-source code 67 | Generic = Token.Generic 68 | 69 | # String and some others are not direct childs of Token. 70 | # alias them: 71 | Token.Token = Token 72 | Token.String = String 73 | Token.Number = Number 74 | 75 | 76 | def is_token_subtype(ttype, other): 77 | """ 78 | Return True if ``ttype`` is a subtype of ``other``. 79 | 80 | exists for backwards compatibility. use ``ttype in other`` now. 81 | """ 82 | return ttype in other 83 | 84 | 85 | def string_to_tokentype(s): 86 | """ 87 | Convert a string into a token type:: 88 | 89 | >>> string_to_token('String.Double') 90 | Token.Literal.String.Double 91 | >>> string_to_token('Token.Literal.Number') 92 | Token.Literal.Number 93 | >>> string_to_token('') 94 | Token 95 | 96 | Tokens that are already tokens are returned unchanged: 97 | 98 | >>> string_to_token(String) 99 | Token.Literal.String 100 | """ 101 | if isinstance(s, _TokenType): 102 | return s 103 | if not s: 104 | return Token 105 | node = Token 106 | for item in s.split('.'): 107 | node = getattr(node, item) 108 | return node 109 | 110 | 111 | # Map standard token types to short names, used in CSS class naming. 112 | # If you add a new item, please be sure to run this file to perform 113 | # a consistency check for duplicate values. 114 | STANDARD_TYPES = { 115 | Token: '', 116 | 117 | Text: '', 118 | Whitespace: 'w', 119 | Error: 'err', 120 | Other: 'x', 121 | 122 | Keyword: 'k', 123 | Keyword.Constant: 'kc', 124 | Keyword.Declaration: 'kd', 125 | Keyword.Namespace: 'kn', 126 | Keyword.Pseudo: 'kp', 127 | Keyword.Reserved: 'kr', 128 | Keyword.Type: 'kt', 129 | 130 | Name: 'n', 131 | Name.Attribute: 'na', 132 | Name.Builtin: 'nb', 133 | Name.Builtin.Pseudo: 'bp', 134 | Name.Class: 'nc', 135 | Name.Constant: 'no', 136 | Name.Decorator: 'nd', 137 | Name.Entity: 'ni', 138 | Name.Exception: 'ne', 139 | Name.Function: 'nf', 140 | Name.Property: 'py', 141 | Name.Label: 'nl', 142 | Name.Namespace: 'nn', 143 | Name.Other: 'nx', 144 | Name.Tag: 'nt', 145 | Name.Variable: 'nv', 146 | Name.Variable.Class: 'vc', 147 | Name.Variable.Global: 'vg', 148 | Name.Variable.Instance: 'vi', 149 | 150 | Literal: 'l', 151 | Literal.Date: 'ld', 152 | 153 | String: 's', 154 | String.Backtick: 'sb', 155 | String.Char: 'sc', 156 | String.Doc: 'sd', 157 | String.Double: 's2', 158 | String.Escape: 'se', 159 | String.Heredoc: 'sh', 160 | String.Interpol: 'si', 161 | String.Other: 'sx', 162 | String.Regex: 'sr', 163 | String.Single: 's1', 164 | String.Symbol: 'ss', 165 | 166 | Number: 'm', 167 | Number.Float: 'mf', 168 | Number.Hex: 'mh', 169 | Number.Integer: 'mi', 170 | Number.Integer.Long: 'il', 171 | Number.Oct: 'mo', 172 | 173 | Operator: 'o', 174 | Operator.Word: 'ow', 175 | 176 | Punctuation: 'p', 177 | 178 | Comment: 'c', 179 | Comment.Multiline: 'cm', 180 | Comment.Preproc: 'cp', 181 | Comment.Single: 'c1', 182 | Comment.Special: 'cs', 183 | 184 | Generic: 'g', 185 | Generic.Deleted: 'gd', 186 | Generic.Emph: 'ge', 187 | Generic.Error: 'gr', 188 | Generic.Heading: 'gh', 189 | Generic.Inserted: 'gi', 190 | Generic.Output: 'go', 191 | Generic.Prompt: 'gp', 192 | Generic.Strong: 'gs', 193 | Generic.Subheading: 'gu', 194 | Generic.Traceback: 'gt', 195 | } 196 | -------------------------------------------------------------------------------- /code_highlight_addon/pygments/util.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pygments.util 4 | ~~~~~~~~~~~~~ 5 | 6 | Utility functions. 7 | 8 | :copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS. 9 | :license: BSD, see LICENSE for details. 10 | """ 11 | 12 | import re 13 | import sys 14 | import codecs 15 | 16 | 17 | split_path_re = re.compile(r'[/\\ ]') 18 | doctype_lookup_re = re.compile(r'''(?smx) 19 | (<\?.*?\?>)?\s* 20 | ]*> 25 | ''') 26 | tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?(?uism)') 27 | 28 | 29 | class ClassNotFound(ValueError): 30 | """ 31 | If one of the get_*_by_* functions didn't find a matching class. 32 | """ 33 | 34 | 35 | class OptionError(Exception): 36 | pass 37 | 38 | 39 | def get_choice_opt(options, optname, allowed, default=None, normcase=False): 40 | string = options.get(optname, default) 41 | if normcase: 42 | string = string.lower() 43 | if string not in allowed: 44 | raise OptionError('Value for option %s must be one of %s' % 45 | (optname, ', '.join(map(str, allowed)))) 46 | return string 47 | 48 | 49 | def get_bool_opt(options, optname, default=None): 50 | string = options.get(optname, default) 51 | if isinstance(string, bool): 52 | return string 53 | elif isinstance(string, int): 54 | return bool(string) 55 | elif not isinstance(string, basestring): 56 | raise OptionError('Invalid type %r for option %s; use ' 57 | '1/0, yes/no, true/false, on/off' % ( 58 | string, optname)) 59 | elif string.lower() in ('1', 'yes', 'true', 'on'): 60 | return True 61 | elif string.lower() in ('0', 'no', 'false', 'off'): 62 | return False 63 | else: 64 | raise OptionError('Invalid value %r for option %s; use ' 65 | '1/0, yes/no, true/false, on/off' % ( 66 | string, optname)) 67 | 68 | 69 | def get_int_opt(options, optname, default=None): 70 | string = options.get(optname, default) 71 | try: 72 | return int(string) 73 | except TypeError: 74 | raise OptionError('Invalid type %r for option %s; you ' 75 | 'must give an integer value' % ( 76 | string, optname)) 77 | except ValueError: 78 | raise OptionError('Invalid value %r for option %s; you ' 79 | 'must give an integer value' % ( 80 | string, optname)) 81 | 82 | 83 | def get_list_opt(options, optname, default=None): 84 | val = options.get(optname, default) 85 | if isinstance(val, basestring): 86 | return val.split() 87 | elif isinstance(val, (list, tuple)): 88 | return list(val) 89 | else: 90 | raise OptionError('Invalid type %r for option %s; you ' 91 | 'must give a list value' % ( 92 | val, optname)) 93 | 94 | 95 | def docstring_headline(obj): 96 | if not obj.__doc__: 97 | return '' 98 | res = [] 99 | for line in obj.__doc__.strip().splitlines(): 100 | if line.strip(): 101 | res.append(" " + line.strip()) 102 | else: 103 | break 104 | return ''.join(res).lstrip() 105 | 106 | 107 | def make_analysator(f): 108 | """ 109 | Return a static text analysation function that 110 | returns float values. 111 | """ 112 | def text_analyse(text): 113 | try: 114 | rv = f(text) 115 | except Exception: 116 | return 0.0 117 | if not rv: 118 | return 0.0 119 | try: 120 | return min(1.0, max(0.0, float(rv))) 121 | except (ValueError, TypeError): 122 | return 0.0 123 | text_analyse.__doc__ = f.__doc__ 124 | return staticmethod(text_analyse) 125 | 126 | 127 | def shebang_matches(text, regex): 128 | """ 129 | Check if the given regular expression matches the last part of the 130 | shebang if one exists. 131 | 132 | >>> from pygments.util import shebang_matches 133 | >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?') 134 | True 135 | >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?') 136 | True 137 | >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?') 138 | False 139 | >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?') 140 | False 141 | >>> shebang_matches('#!/usr/bin/startsomethingwith python', 142 | ... r'python(2\.\d)?') 143 | True 144 | 145 | It also checks for common windows executable file extensions:: 146 | 147 | >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?') 148 | True 149 | 150 | Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does 151 | the same as ``'perl -e'``) 152 | 153 | Note that this method automatically searches the whole string (eg: 154 | the regular expression is wrapped in ``'^$'``) 155 | """ 156 | index = text.find('\n') 157 | if index >= 0: 158 | first_line = text[:index].lower() 159 | else: 160 | first_line = text.lower() 161 | if first_line.startswith('#!'): 162 | try: 163 | found = [x for x in split_path_re.split(first_line[2:].strip()) 164 | if x and not x.startswith('-')][-1] 165 | except IndexError: 166 | return False 167 | regex = re.compile('^%s(\.(exe|cmd|bat|bin))?$' % regex, re.IGNORECASE) 168 | if regex.search(found) is not None: 169 | return True 170 | return False 171 | 172 | 173 | def doctype_matches(text, regex): 174 | """ 175 | Check if the doctype matches a regular expression (if present). 176 | Note that this method only checks the first part of a DOCTYPE. 177 | eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' 178 | """ 179 | m = doctype_lookup_re.match(text) 180 | if m is None: 181 | return False 182 | doctype = m.group(2) 183 | return re.compile(regex).match(doctype.strip()) is not None 184 | 185 | 186 | def html_doctype_matches(text): 187 | """ 188 | Check if the file looks like it has a html doctype. 189 | """ 190 | return doctype_matches(text, r'html\s+PUBLIC\s+"-//W3C//DTD X?HTML.*') 191 | 192 | 193 | _looks_like_xml_cache = {} 194 | def looks_like_xml(text): 195 | """ 196 | Check if a doctype exists or if we have some tags. 197 | """ 198 | key = hash(text) 199 | try: 200 | return _looks_like_xml_cache[key] 201 | except KeyError: 202 | m = doctype_lookup_re.match(text) 203 | if m is not None: 204 | return True 205 | rv = tag_re.search(text[:1000]) is not None 206 | _looks_like_xml_cache[key] = rv 207 | return rv 208 | 209 | # Python 2/3 compatibility 210 | 211 | if sys.version_info < (3,0): 212 | b = bytes = str 213 | u_prefix = 'u' 214 | import StringIO, cStringIO 215 | BytesIO = cStringIO.StringIO 216 | StringIO = StringIO.StringIO 217 | uni_open = codecs.open 218 | else: 219 | import builtins 220 | bytes = builtins.bytes 221 | u_prefix = '' 222 | def b(s): 223 | if isinstance(s, str): 224 | return bytes(map(ord, s)) 225 | elif isinstance(s, bytes): 226 | return s 227 | else: 228 | raise TypeError("Invalid argument %r for b()" % (s,)) 229 | import io 230 | BytesIO = io.BytesIO 231 | StringIO = io.StringIO 232 | uni_open = builtins.open 233 | -------------------------------------------------------------------------------- /code_highlight_addon/resources.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Resource object code 4 | # 5 | # Created: qui 23. Fev 11:41:06 2012 6 | # by: The Resource Compiler for PyQt (Qt v4.7.3) 7 | # 8 | # WARNING! All changes made in this file will be lost! 9 | 10 | from PyQt4 import QtCore 11 | 12 | qt_resource_data = "\ 13 | \x00\x00\x02\x66\ 14 | \x89\ 15 | \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ 16 | \x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xff\x61\ 17 | \x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\x77\x61\x72\x65\ 18 | \x00\x41\x64\x6f\x62\x65\x20\x49\x6d\x61\x67\x65\x52\x65\x61\x64\ 19 | \x79\x71\xc9\x65\x3c\x00\x00\x02\x08\x49\x44\x41\x54\x78\xda\x62\ 20 | \xfc\xff\xff\x3f\x03\x36\xb0\xaf\x81\x75\x1a\x90\xca\x64\xc0\x0d\ 21 | \xd6\x00\xf1\x74\x46\x6c\x06\x00\x35\xd7\x09\x2a\x5a\x37\xea\x47\ 22 | \x2e\xc0\xa9\xfb\xf5\x8d\x1d\x0c\xd7\xd6\x17\x30\x60\x18\x00\xd4\ 23 | \xec\xcd\xca\x25\xb4\xc5\x34\x69\x35\x03\xd3\xdf\x4b\x0c\x7f\x3f\ 24 | \xef\x47\x91\x67\x15\x4d\x67\x78\x75\xe3\x00\xc3\xcd\x1d\xbd\x0c\ 25 | \xff\xff\xff\x73\x66\x41\xd3\xcc\x0c\x72\xb6\x86\x77\x1b\x03\x0b\ 26 | \xdb\x6f\x86\x5f\x2f\x76\xa1\x68\x66\x13\xcf\x66\x78\x79\x75\x37\ 27 | \xc3\xad\xdd\x93\x40\x9a\x6d\x9d\x1a\x7e\x1f\x61\x41\x73\x59\xaf\ 28 | \xb4\x71\xac\xb7\x90\x9c\x3a\xc3\xcf\x67\x1d\x68\x9a\x73\x80\x9a\ 29 | \xf7\xc0\x34\x9b\x03\x35\x9f\x02\x89\x33\x21\xd9\x9e\xc3\x2d\xa2\ 30 | \x92\xaf\x6c\x9f\xce\xf0\xeb\xed\x6a\x90\x22\x38\x66\x11\x0e\x67\ 31 | \x78\x7e\x79\x07\xc3\xcd\x5d\x13\xc0\x7c\x20\xa8\x00\xaa\x77\x05\ 32 | \x31\xc0\x61\x00\xe4\x68\x31\x31\xb3\x5e\x35\x4e\x58\xcd\xc0\xc1\ 33 | \xf9\x89\xe1\xd7\x9b\x25\x0c\x0c\xff\xff\xa2\xb8\x80\x43\xb6\x8e\ 34 | \x81\x91\x55\x12\xcc\x7e\x73\x6b\x37\xc3\xed\x5d\x4d\x0c\x3f\x3f\ 35 | \xbf\x94\x81\x79\x21\x53\xd9\xa9\x82\x81\x83\x8f\x83\x81\xe1\x1f\ 36 | \x23\xd8\xaf\x20\xf0\xf3\xd9\x04\xb8\x01\xff\x7e\x7f\x60\xf8\xfd\ 37 | \xe9\x21\xc3\xdd\x03\xb3\x18\x5e\xdf\x3a\xb2\x1e\x14\x85\x40\x6f\ 38 | \x3c\x85\xbb\x00\x28\x90\x83\x1c\xef\x2a\x8e\xe9\x0c\x12\x9a\x66\ 39 | \x0c\xff\x7e\x3e\x60\x60\xe6\x36\x02\x69\x62\xb8\x7b\x70\x0e\xc3\ 40 | \xef\xef\x1f\x9b\x80\x1a\xeb\x61\xea\xb0\x45\xe3\x64\x29\xc3\xc8\ 41 | \x1c\x90\x01\xff\xff\xbc\x67\xf8\xf5\xe5\x2d\xc3\x1d\xa0\xc6\xb7\ 42 | \x77\x4f\xac\x84\xda\x7a\x10\x45\x03\xc8\x00\x18\xde\x5b\xcf\xd2\ 43 | \x7e\x61\x91\xcb\xff\xdf\x1f\x4f\xfe\xff\xf5\x66\xd3\xff\xc7\x87\ 44 | \x0b\xfe\x1f\x6c\xe5\xff\x0f\x14\xaf\x46\x56\x87\x8c\x91\x35\x57\ 45 | \x9f\x98\xa2\xf5\xff\xfb\x9b\xc3\xff\x3f\xdd\x9f\xf7\xff\xdc\x3c\ 46 | \x53\x90\xc6\xf9\x40\x6c\x86\x4b\x33\xdc\x00\xa0\x22\x9b\x43\x9d\ 47 | \x62\xff\xbf\xbe\xd8\xf7\xff\xc1\xfe\xac\xff\x07\x5a\x78\x40\x9a\ 48 | \x2b\xf0\x69\x84\x61\x46\xa0\x42\x4e\x26\x16\x8e\x6f\xea\x1e\x8d\ 49 | \x0c\xcf\xce\x2f\x62\xf8\xf8\xf4\xea\x74\xa8\x5f\x2f\x33\x10\x01\ 50 | \x40\xd1\x68\xc0\x23\xae\x01\x4c\xdb\x75\x0c\xff\xfe\xfc\x74\xc0\ 51 | \x08\x24\x42\x00\xea\x05\x4b\x90\x4b\x88\x71\x32\x3a\x06\x08\x30\ 52 | \x00\x22\xac\x76\xb2\xc4\x23\x5a\xa3\x00\x00\x00\x00\x49\x45\x4e\ 53 | \x44\xae\x42\x60\x82\ 54 | " 55 | 56 | qt_resource_name = "\ 57 | \x00\x05\ 58 | \x00\x6f\xa6\x53\ 59 | \x00\x69\ 60 | \x00\x63\x00\x6f\x00\x6e\x00\x73\ 61 | \x00\x0f\ 62 | \x01\x4c\xd7\xa7\ 63 | \x00\x62\ 64 | \x00\x75\x00\x74\x00\x74\x00\x6f\x00\x6e\x00\x2d\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ 65 | " 66 | 67 | qt_resource_struct = "\ 68 | \x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ 69 | \x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\ 70 | \x00\x00\x00\x10\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ 71 | " 72 | 73 | def qInitResources(): 74 | QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) 75 | 76 | def qCleanupResources(): 77 | QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) 78 | 79 | qInitResources() 80 | -------------------------------------------------------------------------------- /code_highlight_addon/resources.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | icons/button-icon.png 4 | 5 | --------------------------------------------------------------------------------