Guess the alias of the Pygments lexer to use based on a path and an optional string of code. If code is supplied, it will use a combination of the code and the filename to determine the best lexer to use. For example, if the file is ``index.html`` and the file contains Django
(cls, path: str, code: Optional[str] = None)
| 381 | |
| 382 | @classmethod |
| 383 | def guess_lexer(cls, path: str, code: Optional[str] = None) -> str: |
| 384 | """Guess the alias of the Pygments lexer to use based on a path and an optional string of code. |
| 385 | If code is supplied, it will use a combination of the code and the filename to determine the |
| 386 | best lexer to use. For example, if the file is ``index.html`` and the file contains Django |
| 387 | templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no |
| 388 | templating language is used, the "html" lexer will be used. If no string of code |
| 389 | is supplied, the lexer will be chosen based on the file extension.. |
| 390 | |
| 391 | Args: |
| 392 | path (AnyStr): The path to the file containing the code you wish to know the lexer for. |
| 393 | code (str, optional): Optional string of code that will be used as a fallback if no lexer |
| 394 | is found for the supplied path. |
| 395 | |
| 396 | Returns: |
| 397 | str: The name of the Pygments lexer that best matches the supplied path/code. |
| 398 | """ |
| 399 | lexer: Optional[Lexer] = None |
| 400 | lexer_name = "default" |
| 401 | if code: |
| 402 | try: |
| 403 | lexer = guess_lexer_for_filename(path, code) |
| 404 | except ClassNotFound: |
| 405 | pass |
| 406 | |
| 407 | if not lexer: |
| 408 | try: |
| 409 | _, ext = os.path.splitext(path) |
| 410 | if ext: |
| 411 | extension = ext.lstrip(".").lower() |
| 412 | lexer = get_lexer_by_name(extension) |
| 413 | except ClassNotFound: |
| 414 | pass |
| 415 | |
| 416 | if lexer: |
| 417 | if lexer.aliases: |
| 418 | lexer_name = lexer.aliases[0] |
| 419 | else: |
| 420 | lexer_name = lexer.name |
| 421 | |
| 422 | return lexer_name |
| 423 | |
| 424 | def _get_base_style(self) -> Style: |
| 425 | """Get the base style.""" |
no outgoing calls