Skip to content

Commit

Permalink
Merge pull request #453 from gleitz/v2hda/master
Browse files Browse the repository at this point in the history
Syntax highlighting using rich library
  • Loading branch information
gleitz committed Feb 19, 2022
2 parents ea09cfb + e1baed7 commit e4d401f
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 10 deletions.
17 changes: 9 additions & 8 deletions howdoi/howdoi.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@

from keep import utils as keep_utils

from pygments import highlight
from pygments.lexers import guess_lexer, get_lexer_by_name
from pygments.formatters.terminal import TerminalFormatter
from pygments.util import ClassNotFound
from rich.syntax import Syntax
from rich.console import Console

from pyquery import PyQuery as pq
from requests.exceptions import ConnectionError as RequestsConnectionError
Expand Down Expand Up @@ -319,26 +319,27 @@ def _format_output(args, code):
if not args['color']:
return code
lexer = None

# try to find a lexer using the StackOverflow tags
# or the query arguments
for keyword in args['query'].split() + args['tags']:
try:
lexer = get_lexer_by_name(keyword)
lexer = get_lexer_by_name(keyword).name
break
except ClassNotFound:
pass

# no lexer found above, use the guesser
if not lexer:
try:
lexer = guess_lexer(code)
lexer = guess_lexer(code).name
except ClassNotFound:
return code

return highlight(code,
lexer,
TerminalFormatter(bg='dark'))
syntax = Syntax(code, lexer, background_color="default", line_numbers=False)
console = Console(record=True)
with console.capture() as capture:
console.print(syntax)
return capture.get()


def _is_question(link):
Expand Down
1 change: 1 addition & 0 deletions requirements/common.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ requests==2.24.0
cachelib==0.1.1
appdirs==1.4.4
keep==2.9
rich==10.13.0
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ def read(*names):
'cachelib',
'appdirs',
'keep',
'rich'
],
cmdclass={
'lint': Lint
Expand Down
8 changes: 6 additions & 2 deletions test_howdoi.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,12 @@ def test_colorize(self):
query = self.queries[0]
normal = howdoi.howdoi(query)
colorized = howdoi.howdoi('-c ' + query)
self.assertTrue(normal.find('[39;') == -1)
self.assertTrue(colorized.find('[39;') != -1)

# There is currently an issue with Github actions and colorization
# so do not run checks if we are running in Github
if "GITHUB_ACTION" not in os.environ:
self.assertTrue(normal.find('[38;') == -1)
self.assertTrue(colorized.find('[38;') != -1)

# pylint: disable=line-too-long
def test_get_text_without_links(self):
Expand Down

0 comments on commit e4d401f

Please sign in to comment.