From 44e36aaf6f8c5b4aba4d66bcf895b25c3b5fa32e Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Sun, 17 Sep 2023 16:41:40 +0100 Subject: [PATCH] Add default lexer --- rich/syntax.py | 23 ++++++++++++++--------- tests/test_syntax.py | 2 +- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/rich/syntax.py b/rich/syntax.py index aac30b970..618e0459f 100644 --- a/rich/syntax.py +++ b/rich/syntax.py @@ -379,7 +379,7 @@ def guess_lexer(cls, path: str, code: Optional[str] = None) -> str: str: The name of the Pygments lexer that best matches the supplied path/code. """ lexer: Optional[Lexer] = None - lexer_name = "text" + lexer_name = "default" if code: try: lexer = guess_lexer_for_filename(path, code) @@ -421,7 +421,7 @@ def _get_token_color(self, token_type: TokenType) -> Optional[Color]: return style.color @property - def lexer(self) -> Lexer: + def lexer(self) -> Optional[Lexer]: """The lexer for this syntax, or None if no lexer was found. Tries to find the lexer by name if a string was passed to the constructor. @@ -437,12 +437,17 @@ def lexer(self) -> Lexer: tabsize=self.tab_size, ) except ClassNotFound: - return get_lexer_by_name( - "text", - stripnl=False, - ensurenl=True, - tabsize=self.tab_size, - ) + return None + + @property + def default_lexer(self) -> Lexer: + """A Pygments Lexer to use if one is not specified or invalid.""" + return get_lexer_by_name( + "text", + stripnl=False, + ensurenl=True, + tabsize=self.tab_size, + ) def highlight( self, @@ -472,7 +477,7 @@ def highlight( ) _get_theme_style = self._theme.get_style_for_token - lexer = self.lexer + lexer = self.lexer or self.default_lexer if lexer is None: text.append(code) diff --git a/tests/test_syntax.py b/tests/test_syntax.py index 985c3f2d5..da7c3715d 100644 --- a/tests/test_syntax.py +++ b/tests/test_syntax.py @@ -356,7 +356,7 @@ def test_from_path_lexer_override_invalid_lexer(): try: os.write(fh, b"import this\n") syntax = Syntax.from_path(path, lexer="blah") - assert syntax.lexer.name == "Text only" + assert syntax.lexer is None assert syntax.code == "import this\n" finally: os.remove(path)