Colorize output using Pygment lexers.

This commit is contained in:
Lars Yencken 2013-08-21 17:00:24 +10:00
parent 17b2148d6e
commit c6bb350a13
2 changed files with 26 additions and 3 deletions

26
cheat
View File

@ -2,6 +2,11 @@
import os import os
import sys import sys
from pygments import highlight
from pygments.util import ClassNotFound
from pygments.lexers import get_lexer_for_filename, TextLexer
from pygments.formatters import TerminalFormatter
def cheat_directories(): def cheat_directories():
"Assembles a list of directories containing cheatsheets." "Assembles a list of directories containing cheatsheets."
@ -58,13 +63,30 @@ def main():
# print the cheatsheet if it exists # print the cheatsheet if it exists
if keyphrase in cheatsheets: if keyphrase in cheatsheets:
filename = os.path.join(cheatsheets[keyphrase], keyphrase) filename = os.path.join(cheatsheets[keyphrase], keyphrase)
with open(filename, 'r') as cheatsheet: pretty_print(filename)
print cheatsheet.read()
# if it does not, say so # if it does not, say so
else: else:
print 'No cheatsheet found for %s.' % keyphrase print 'No cheatsheet found for %s.' % keyphrase
def pretty_print(filename):
try:
if os.path.splitext(filename)[1]:
lexer = get_lexer_for_filename(filename)
else:
# shell is a sensible default when there is no extension
lexer = get_lexer_for_filename(filename + '.sh')
except ClassNotFound:
lexer = TextLexer()
with open(filename) as istream:
code = istream.read()
fmt = TerminalFormatter()
highlight(code, lexer, fmt, sys.stdout)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -5,12 +5,13 @@ import os
setup(name='cheat', setup(name='cheat',
version='1.0', version='1.0',
description='Create and view interactive cheatsheets on the command-line', description='Create and view interactive cheatsheets on the command-line', # nopep8
author='Chris Lane', author='Chris Lane',
author_email='chris@chris-allen-lane.com', author_email='chris@chris-allen-lane.com',
url='https://github.com/chrisallenlane/cheat', url='https://github.com/chrisallenlane/cheat',
packages=['cheatsheets'], packages=['cheatsheets'],
package_data={'cheatsheets': [f for f in os.listdir('cheatsheets') package_data={'cheatsheets': [f for f in os.listdir('cheatsheets')
if '.' not in f]}, if '.' not in f]},
install_requires=['Pygments>=1.6'],
scripts=['cheat'] scripts=['cheat']
) )