Code Syntax Highlighter

 pip install pygments


from pygments import highlight
from pygments.lexers import guess_lexer, PythonLexer, JavascriptLexer, CLexer
from pygments.formatters import TerminalFormatter, HtmlFormatter

# Function to highlight code in terminal
def highlight_code_terminal(code, language="python"):
    # Choose lexer based on language
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    highlighted_code = highlight(code, lexer, TerminalFormatter())
    return highlighted_code


# Function to highlight code and save as HTML
def highlight_code_html(code, language="python", output_file="highlighted_code.html"):
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    formatter = HtmlFormatter(full=True, style="monokai")
    highlighted_code = highlight(code, lexer, formatter)

    # Save to an HTML file
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(highlighted_code)
    
    print(f"✅ Highlighted code saved to {output_file}")

from pygments import highlight
from pygments.lexers import guess_lexer, PythonLexer, JavascriptLexer, CLexer
from pygments.formatters import TerminalFormatter, HtmlFormatter

# Function to highlight code in terminal
def highlight_code_terminal(code, language="python"):
    # Choose lexer based on language
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    highlighted_code = highlight(code, lexer, TerminalFormatter())
    return highlighted_code


# Function to highlight code and save as HTML
def highlight_code_html(code, language="python", output_file="highlighted_code.html"):
    lexer = {
        "python": PythonLexer(),
        "javascript": JavascriptLexer(),
        "c": CLexer(),
    }.get(language.lower(), guess_lexer(code))

    formatter = HtmlFormatter(full=True, style="monokai")
    highlighted_code = highlight(code, lexer, formatter)

    # Save to an HTML file
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(highlighted_code)
    
    print(f"✅ Highlighted code saved to {output_file}")


# Example usage
if __name__ == "__main__":
    code_sample = """
    def greet(name):
        print(f"Hello, {name}!")
    
    greet("abc")
    """

    print("🎨 Terminal Highlighted Code:")
    print(highlight_code_terminal(code_sample, "python"))

    highlight_code_html(code_sample, "python")


No comments: