Skip to content

Commit 44e36aa

Browse files
committed
Add default lexer
1 parent 32ec768 commit 44e36aa

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

rich/syntax.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:
379379
str: The name of the Pygments lexer that best matches the supplied path/code.
380380
"""
381381
lexer: Optional[Lexer] = None
382-
lexer_name = "text"
382+
lexer_name = "default"
383383
if code:
384384
try:
385385
lexer = guess_lexer_for_filename(path, code)
@@ -421,7 +421,7 @@ def _get_token_color(self, token_type: TokenType) -> Optional[Color]:
421421
return style.color
422422

423423
@property
424-
def lexer(self) -> Lexer:
424+
def lexer(self) -> Optional[Lexer]:
425425
"""The lexer for this syntax, or None if no lexer was found.
426426
427427
Tries to find the lexer by name if a string was passed to the constructor.
@@ -437,12 +437,17 @@ def lexer(self) -> Lexer:
437437
tabsize=self.tab_size,
438438
)
439439
except ClassNotFound:
440-
return get_lexer_by_name(
441-
"text",
442-
stripnl=False,
443-
ensurenl=True,
444-
tabsize=self.tab_size,
445-
)
440+
return None
441+
442+
@property
443+
def default_lexer(self) -> Lexer:
444+
"""A Pygments Lexer to use if one is not specified or invalid."""
445+
return get_lexer_by_name(
446+
"text",
447+
stripnl=False,
448+
ensurenl=True,
449+
tabsize=self.tab_size,
450+
)
446451

447452
def highlight(
448453
self,
@@ -472,7 +477,7 @@ def highlight(
472477
)
473478
_get_theme_style = self._theme.get_style_for_token
474479

475-
lexer = self.lexer
480+
lexer = self.lexer or self.default_lexer
476481

477482
if lexer is None:
478483
text.append(code)

tests/test_syntax.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ def test_from_path_lexer_override_invalid_lexer():
356356
try:
357357
os.write(fh, b"import this\n")
358358
syntax = Syntax.from_path(path, lexer="blah")
359-
assert syntax.lexer.name == "Text only"
359+
assert syntax.lexer is None
360360
assert syntax.code == "import this\n"
361361
finally:
362362
os.remove(path)

0 commit comments

Comments
 (0)