def _guess_lexer(cls, filename: str, code: str) -> str: ext = os.path.splitext(filename)[-1] if not ext: # No extension, look at first line to see if it is a hashbang # Note, this is an educated guess and not a guarantee # If it fails, the only downside is that the code is highlighted strangely new_line_index = code.index("\n") first_line = code[:new_line_index] if new_line_index != -1 else code if first_line.startswith("#!") and "python" in first_line.lower(): return "python" lexer_name = (cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name) return lexer_name
def guess_lexer(cls, path: str, code: Optional[str] = None) -> str: """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 templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no templating language is used, the "html" lexer will be used. If no string of code is supplied, the lexer will be chosen based on the file extension.. Args: path (AnyStr): The path to the file containing the code you wish to know the lexer for. code (str, optional): Optional string of code that will be used as a fallback if no lexer is found for the supplied path. Returns: str: The name of the Pygments lexer that best matches the supplied path/code. """ lexer: Optional[Lexer] = None lexer_name = "default" if code: try: lexer = guess_lexer_for_filename(path, code) except ClassNotFound: pass if not lexer: try: _, ext = os.path.splitext(path) if ext: extension = ext.lstrip(".").lower() lexer = get_lexer_by_name(extension) except ClassNotFound: pass if lexer: if lexer.aliases: lexer_name = lexer.aliases[0] else: lexer_name = lexer.name return lexer_name
def from_path( cls, path: str, encoding: str = "utf-8", theme: Union[str, SyntaxTheme] = DEFAULT_THEME, dedent: bool = False, line_numbers: bool = False, line_range: Optional[Tuple[int, int]] = None, start_line: int = 1, highlight_lines: Optional[Set[int]] = None, code_width: Optional[int] = None, tab_size: int = 4, word_wrap: bool = False, background_color: Optional[str] = None, indent_guides: bool = False, ) -> "Syntax": """Construct a Syntax object from a file. Args: path (str): Path to file to highlight. encoding (str): Encoding of file. theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs". dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True. line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False. start_line (int, optional): Starting number for line numbers. Defaults to 1. line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render. highlight_lines (Set[int]): A set of line numbers to highlight. code_width: Width of code to render (not including line numbers), or ``None`` to use all available width. tab_size (int, optional): Size of tabs. Defaults to 4. word_wrap (bool, optional): Enable word wrapping of code. background_color (str, optional): Optional background color, or None to use theme color. Defaults to None. indent_guides (bool, optional): Show indent guides. Defaults to False. Returns: [Syntax]: A Syntax object that may be printed to the console """ with open(path, "rt", encoding=encoding) as code_file: code = code_file.read() lexer = None lexer_name = "default" try: _, ext = os.path.splitext(path) if ext: extension = ext.lstrip(".").lower() lexer = get_lexer_by_name(extension) lexer_name = lexer.name except ClassNotFound: pass if lexer is None: try: lexer_name = guess_lexer_for_filename(path, code).name except ClassNotFound: pass return cls( code, lexer_name, theme=theme, dedent=dedent, line_numbers=line_numbers, line_range=line_range, start_line=start_line, highlight_lines=highlight_lines, code_width=code_width, tab_size=tab_size, word_wrap=word_wrap, background_color=background_color, indent_guides=indent_guides, )