diff --git a/cheat/sheets.py b/cheat/sheets.py index 61b851d..4d494ee 100644 --- a/cheat/sheets.py +++ b/cheat/sheets.py @@ -2,6 +2,7 @@ import os from cheat import cheatsheets from cheat.utils import die +from cheat.utils import highlight def default_path(): """ Returns the default cheatsheet path """ @@ -84,7 +85,12 @@ def search(term): for cheatsheet in sorted(get().items()): match = '' for line in open(cheatsheet[1]): - if lowered_term in line.lower(): + if term in line: + + # highlight the search term if CHEATCOLORS equals true + if 'CHEATCOLORS' in os.environ: + line = highlight(term, line); + match += ' ' + line if match != '': diff --git a/cheat/utils.py b/cheat/utils.py index a6830ac..11e3d77 100644 --- a/cheat/utils.py +++ b/cheat/utils.py @@ -1,8 +1,24 @@ from __future__ import print_function import os -import sys import subprocess +import sys +def highlight(needle, haystack): + """ Highlights a search term matched in a line """ + + # only colorize if so configured + if not 'CHEATCOLORS' in os.environ or os.environ.get('CHEATCOLORS') != 'true': + return sheet_content + + try: + from termcolor import colored + + # if pygments can't load, just return the uncolorized text + except ImportError: + return haystack + + # colorize the search term, and replace it within the surrounding line + return haystack.replace(needle, colored(needle, 'blue')); def colorize(sheet_content): """ Colorizes cheatsheet content if so configured """