This repository has been archived on 2024-05-23. You can view files and clone it, but cannot push or open issues or pull requests.
C-Sy-G/Syntax Highlighting.py

189 lines
6.7 KiB
Python

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
import os
# Define the code snippets and their respective languages
code_snippets = {
"bash": 'echo "This is an example"',
"c": """
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("This is an example");
return 0;
}
""",
"html": """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Code Example</title>
<style type="text/css">
body {
margin: 40px auto;
max-width: 650px;
line-height: 1.6;
font-size: 18px;
padding: 0 10px;
color: #EBDBB2;
background-color: #1d2021
}
</style>
</head>
<body>
<p>This is an example</p>
</body>
</html>
"""
}
# Define colors and weights for different classes (modify as needed)
class_colors = {
"hll": "#ffffcc",
"c": "#3D7B7B", # Comment
"k": "#008000", # Keyword
"o": "#666666", # Operator
"ch": "#3D7B7B", # Comment.Hashbang
"cm": "#3D7B7B", # Comment.Multiline
"cp": "#9C6500", # Comment.Preproc
"cpf": "#3D7B7B", # Comment.PreprocFile
"c1": "#3D7B7B", # Comment.Single
"cs": "#3D7B7B", # Comment.Special
"gd": "#A00000", # Generic.Deleted
"gr": "#E40000", # Generic.Error
"gh": "#000080", # Generic.Heading
"gi": "#008400", # Generic.Inserted
"go": "#717171", # Generic.Output
"gp": "#000080", # Generic.Prompt
"gu": "#800080", # Generic.Subheading
"gt": "#0044DD", # Generic.Traceback
"kc": "#008000", # Keyword.Constant
"kd": "#008000", # Keyword.Declaration
"kn": "#008000", # Keyword.Namespace
"kp": "#008000", # Keyword.Pseudo
"kr": "#008000", # Keyword.Reserved
"kt": "#B00040", # Keyword.Type
"m": "#666666", # Literal.Number
"s": "#BA2121", # Literal.String
"na": "#687822", # Name.Attribute
"nb": "#008000", # Name.Builtin
"nc": "#0000FF", # Name.Class
"no": "#880000", # Name.Constant
"nd": "#AA22FF", # Name.Decorator
"ni": "#717171", # Name.Entity
"ne": "#CB3F38", # Name.Exception
"nf": "#0000FF", # Name.Function
"nl": "#767600", # Name.Label
"nn": "#0000FF", # Name.Namespace
"nt": "#008000", # Name.Tag
"nv": "#19177C", # Name.Variable
"ow": "#AA22FF", # Operator.Word
"w": "#bbbbbb", # Text.Whitespace
"mb": "#666666", # Literal.Number.Bin
"mf": "#666666", # Literal.Number.Float
"mh": "#666666", # Literal.Number.Hex
"mi": "#666666", # Literal.Number.Integer
"mo": "#666666", # Literal.Number.Oct
"sa": "#BA2121", # Literal.String.Affix
"sb": "#BA2121", # Literal.String.Backtick
"sc": "#BA2121", # Literal.String.Char
"dl": "#BA2121", # Literal.String.Delimiter
"sd": "#BA2121", # Literal.String.Doc
"s2": "#BA2121", # Literal.String.Double
"se": "#AA5D1F", # Literal.String.Escape
"sh": "#BA2121", # Literal.String.Heredoc
"si": "#A45A77", # Literal.String.Interpol
"sx": "#008000", # Literal.String.Other
"sr": "#A45A77", # Literal.String.Regex
"s1": "#BA2121", # Literal.String.Single
"ss": "#19177C", # Literal.String.Symbol
"bp": "#008000", # Name.Builtin.Pseudo
"fm": "#0000FF", # Name.Function.Magic
"vc": "#19177C", # Name.Variable.Class
"vg": "#19177C", # Name.Variable.Global
"vi": "#19177C", # Name.Variable.Instance
"vm": "#19177C", # Name.Variable.Magic
"il": "#666666", # Literal.Number.Integer.Long
}
# Define weights for different classes (modify as needed)
class_weights = {
"c": "font-style: italic", # Comment
"k": "font-weight: bold", # Keyword
"ch": "font-style: italic", # Comment.Hashbang
"cm": "font-style: italic", # Comment.Multiline
"cpf": "font-style: italic", # Comment.PreprocFile
"c1": "font-style: italic", # Comment.Single
"cs": "font-style: italic", # Comment.Special
"ge": "font-style: italic", # Generic.Emph
"ges": "font-weight: bold", # Generic.EmphStrong
"gh": "font-weight: bold", # Generic.Heading
"gp": "font-weight: bold", # Generic.Prompt
"gs": "font-weight: bold", # Generic.Strong
"gu": "font-weight: bold", # Generic.Subheading
"kc": "font-weight: bold", # Keyword.Constant
"kd": "font-weight: bold", # Keyword.Declaration
"kn": "font-weight: bold", # Keyword.Namespace
"kr": "font-weight: bold", # Keyword.Reserved
"nc": "font-weight: bold", # Name.Class
"ni": "font-weight: bold", # Name.Entity
"ne": "font-weight: bold", # Name.Exception
"nn": "font-weight: bold", # Name.Namespace
"nt": "font-weight: bold", # Name.Tag
"ow": "font-weight: bold", # Operator.Word
"sd": "font-style: italic", # Literal.String.Doc
"se": "font-weight: bold", # Literal.String.Escape
"si": "font-weight: bold", # Literal.String.Interpol
}
# Create a directory to store the generated HTML files
output_dir = "highlighted_code"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Generate HTML files with syntax-highlighted code snippets
for snippet_name, code in code_snippets.items():
# Choose lexer based on the language
if snippet_name == "c":
lexer = get_lexer_by_name("c")
elif snippet_name == "bash":
lexer = get_lexer_by_name("bash")
elif snippet_name == "html":
lexer = get_lexer_by_name("html")
else:
raise ValueError(f"No lexer for language '{snippet_name}' found.")
# Generate class styles for the specific language
css_class_definitions = []
# Create a set of all class names
all_classes = sorted(set(class_colors.keys()) | set(class_weights.keys()))
# Add class definitions for each class, ensuring alphabetical order
for cls in all_classes:
color = class_colors.get(cls)
weight = class_weights.get(cls)
if color is not None:
css_class_definitions.append(f".{cls} {{ color: {color}; {weight or ''} }}")
elif weight is not None:
css_class_definitions.append(f".{cls} {{ {weight} }}")
html_class_definitions = "\n".join(css_class_definitions)
# Highlight the code
formatter = HtmlFormatter()
highlighted_code = highlight(code, lexer, formatter)
# Combine CSS styles, HTML class definitions, and highlighted code
html_code = f"<style>\n{html_class_definitions}\n</style>\n{highlighted_code}"
# Write the HTML code to a file
output_file_path = os.path.join(output_dir, f"{snippet_name}.html")
with open(output_file_path, "w") as f:
f.write(html_code)
print(f"Generated HTML file for '{snippet_name}' code snippet: {output_file_path}")