Skip to content

Commit

Permalink
Add default lexer
Browse files Browse the repository at this point in the history
  • Loading branch information
willmcgugan committed Sep 17, 2023
1 parent 32ec768 commit 44e36aa
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
23 changes: 14 additions & 9 deletions rich/syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 44e36aa

Please sign in to comment.