forked from n8gray/QLColorCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolorize.py
More file actions
executable file
·84 lines (71 loc) · 2.31 KB
/
colorize.py
File metadata and controls
executable file
·84 lines (71 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python
#
# colorize.py
# QLColorCode
#
# Created by Nathaniel Gray on 12/10/07.
# Copyright (c) 2007 Nathaniel Gray. All rights reserved.
#
import os, sys
rsrcDir = sys.argv[1]
#os.chdir( rsrcDir + "/pygments")
#sys.path += '.'
import fnmatch
import pygments
from pygments.lexers import get_lexer_for_filename, get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments import highlight
# If you want a different style change this to a string with one of these (e.g. "trac")
# Styles: manni, perldoc, borland, colorful, default, murphy, trac, fruity, autumn,
# emacs, pastie, friendly, native
#style = "autumn"
from nautumn import NautumnStyle
style = NautumnStyle
overrides = (
# pattern, pre-filter, lexer
('*.plist', '/usr/bin/plutil -convert xml1 -o - "%s"', 'xml'),
('*.mm', None, 'objc'),
('*.c[cp]', None, 'c++'),
('*.hh', None, 'c++'),
('*.command', None, 'sh')
)
target = sys.argv[2]
thumb = sys.argv[3]
thumbBytes = 1024*4 # Only read this many bytes for thumbnail generation
if thumb == "1":
limit = thumbBytes
else:
limit = -1
# Use a custom formatter to add style info for the 'pre' tag
class customHtmlFormatter(HtmlFormatter):
def wrap(self, source, outfile):
return self._wrap_code(source)
def _wrap_code(self, source):
yield 0, '<div class="highlight"><pre style="font-family: Monaco; font-size: small">'
for i, t in source:
#if i == 1:
# it's a line of formatted code
#t += '\n'
yield i, t
yield 0, '</pre></div>'
# Find a matching lexer
match = None
for pattern, filter, lexer in overrides:
if fnmatch.fnmatch(target, pattern):
match = (filter % (target), get_lexer_by_name(lexer))
if match == None:
try:
match = (None, get_lexer_for_filename(target))
except ClassNotFound:
match = (None, get_lexer_for_filename("foo.txt"))
# Create the formatter
formatter = customHtmlFormatter(outencoding="UTF-8", full=True, style=style)
# Ok, everything is set up. Read the file, possibly filtering it
if match[0] == None:
inFile = open(target, "rt")
else:
(childIn, inFile) = os.popen4(match[0])
childIn.close()
contents = inFile.read(limit)
inFile.close()
highlight(contents, match[1], formatter, sys.stdout)