ObjDocumentCode is a document delegate class for generating syntax-highlighted code preview icons. It renders the first lines of source files as pygments-highlighted images using the monokai theme, supporting a wide range of programming and markup languages.
Module: factory.core/ObjDocumentCode.py
Inherits from: ObjDocumentDelegate.ObjDocumentDelegate
Test file: resource.test/pytests/factory.core/test_ObjDocumentCode.py
This module enables developers to:
Supports 13 languages and formats:
LEXER_MAP = {
"HTML": HtmlLexer,
"JS": JavascriptLexer,
"CSS": CssLexer,
"SCSS": ScssLexer,
"PY": PythonLexer,
"TS": TypeScriptLexer,
"JSON": JsonLexer,
"XML": XmlLexer,
"YAML": YamlLexer,
"SQL": SqlLexer,
"MD": MarkdownLexer,
"TXT": TextLexer,
"LOG": TextLexer,
}
File Extension Mapping:
.html → HTML.js → JavaScript.css → CSS.scss → SCSS.py → Python.ts → TypeScript.json → JSON.xml → XML.yaml, .yml → YAML.sql → SQL.md → Markdown.txt → Plain text.log → Plain text__init__(DB: int = 0) -> NoneInitializes the ObjDocumentCode instance.
Parameters:
DB (int, optional): Database connection identifier (default: 0)Initialization:
_IsA to "ObjDocumentCode"load_code(file_path: str, max_lines: int = 25) -> strReads the first N lines of a code file.
Parameters:
file_path (str): Path to the code filemax_lines (int, optional): Maximum number of lines to read (default: 25)Returns:
str: Joined string of the first max_lines linesFeatures:
Example:
code_handler = ObjDocumentCode()
# Load first 25 lines (default)
code = code_handler.load_code("/src/app.py")
# Load first 10 lines
code = code_handler.load_code("/src/config.json", max_lines=10)
# Load first 50 lines
code = code_handler.load_code("/src/utils.js", max_lines=50)
_get_lexer(language: str)Returns the pygments lexer for the given language key.
Parameters:
language (str): Language key (e.g., "PY", "JS", "HTML")Returns:
TextLexer if language is unknown (fallback)Case Handling:
Example:
code_handler = ObjDocumentCode()
# Get Python lexer
lexer = code_handler._get_lexer("PY")
# Get JavaScript lexer (case-insensitive)
lexer = code_handler._get_lexer("js")
# Unknown language returns TextLexer
lexer = code_handler._get_lexer("UNKNOWN")
generate_preview(code: str, language: str, output_path: str) -> boolRenders syntax-highlighted code as an image using pygments ImageFormatter.
Parameters:
code (str): Source code to highlightlanguage (str): Language key for lexer selectionoutput_path (str): Path where preview image will be savedReturns:
True if preview generation succeededFalse if an exception occurredImageFormatter Settings:
Example:
code_handler = ObjDocumentCode()
# Python code preview
python_code = '''
def hello_world():
print("Hello, World!")
'''
success = code_handler.generate_preview(
python_code,
"PY",
"/output/code_preview.png"
)
# JavaScript code preview
js_code = 'const x = 42;\nconsole.log(x);'
code_handler.generate_preview(js_code, "JS", "/output/js_preview.png")
_do_generate_icon(input_path: str, output_path: str, icon_size: int) -> NoneInternal method that loads a code file and generates a square thumbnail icon.
Parameters:
input_path (str): Path to the input code fileoutput_path (str): Path where the icon will be savedicon_size (int): Desired size of the square icon in pixelsProcess Flow:
load_code() to read file contentsgenerate_preview() to create highlighted imageDocumentTools.resize_to_square() to resize to square thumbnailExample:
code_handler = ObjDocumentCode()
# Generate 128x128 thumbnail for Python file
code_handler._do_generate_icon(
"/src/main.py",
"/thumbnails/main_thumb.png",
128
)
# Generate 256x256 thumbnail for JavaScript file
code_handler._do_generate_icon(
"/src/app.js",
"/thumbnails/app_thumb.png",
256
)
from ObjDocumentCode import ObjDocumentCode
# Create instance
code = ObjDocumentCode()
# Generate preview for Python file
code.generate_preview(
"def hello():\n print('Hello')",
"PY",
"/output/python_preview.png"
)
from ObjDocumentCode import ObjDocumentCode
code = ObjDocumentCode()
# Generate 200x200 thumbnail
code._do_generate_icon(
"/src/utils.py",
"/thumbnails/utils.png",
200
)
from ObjDocumentCode import ObjDocumentCode
import os
code = ObjDocumentCode()
source_dir = "/src"
output_dir = "/thumbnails"
code_extensions = (".py", ".js", ".css", ".html", ".json", ".md")
for filename in os.listdir(source_dir):
if filename.endswith(code_extensions):
input_path = os.path.join(source_dir, filename)
output_name = os.path.splitext(filename)[0] + "_thumb.png"
output_path = os.path.join(output_dir, output_name)
try:
code._do_generate_icon(input_path, output_path, 128)
print(f"Generated thumbnail for {filename}")
except Exception as e:
print(f"Failed for {filename}: {e}")
from ObjDocumentCode import ObjDocumentCode
code = ObjDocumentCode()
# Load only first 10 lines for preview
code_text = code.load_code("/src/large_file.py", max_lines=10)
# Generate preview
code.generate_preview(code_text, "PY", "/output/preview.png")
from ObjDocumentCode import ObjDocumentCode
code = ObjDocumentCode()
files = [
("/src/app.py", "PY"),
("/src/config.json", "JSON"),
("/src/styles.css", "CSS"),
("/src/readme.md", "MD"),
("/src/query.sql", "SQL"),
]
for file_path, lang in files:
code_text = code.load_code(file_path)
output = f"/previews/{os.path.basename(file_path)}.png"
code.generate_preview(code_text, lang, output)
The module has comprehensive test coverage including:
| Test Case | Description | Status |
|---|---|---|
test_isa_set |
Validates _IsA attribute initialization | ✓ |
test_has_html through test_has_log |
Tests LEXER_MAP completeness | ✓ |
test_total_count |
Verifies 13 supported languages | ✓ |
test_known_language |
Tests correct lexer selection | ✓ |
test_case_insensitive |
Verifies case-insensitive lookup | ✓ |
test_unknown_language_returns_text |
Tests fallback to TextLexer | ✓ |
test_python_lexer through test_log_returns_text_lexer |
Tests all lexers | ✓ |
test_reads_file_content |
Tests file content loading | ✓ |
test_respects_max_lines |
Tests line limit enforcement | ✓ |
test_empty_file |
Tests empty file handling | ✓ |
test_generates_image |
Tests preview generation | ✓ |
test_uses_monokai_style |
Verifies monokai theme usage | ✓ |
test_returns_false_on_error |
Tests error handling | ✓ |
test_delegates_to_load_and_preview |
Tests icon generation pipeline | ✓ |
test_uses_extension_for_language |
Tests language detection | ✓ |
test_falls_back_to_default_language |
Tests fallback to HTML | ✓ |
test_handles_error |
Tests error logging | ✓ |
Test file location: resource.test/pytests/factory.core/test_ObjDocumentCode.py
Run tests:
pytest resource.test/pytests/factory.core/test_ObjDocumentCode.py -v
pygments - Syntax highlighting libraryObjDocumentDelegate - Base delegate classObjDocumentTools.DocumentTools - Thumbnail resizing utilitiesPygments Components:
pygments.highlight - Main highlighting functionpygments.lexers - Language-specific lexerspygments.formatters.ImageFormatter - Image output formatterpygments.styles.get_style_by_name - Style loadingThe monokai theme is a popular dark color scheme:
from ObjDocumentCode import ObjDocumentCode
import os
class CodePreviewGenerator:
def __init__(self):
self.code_handler = ObjDocumentCode()
self.supported_extensions = {
".py": "PY", ".js": "JS", ".css": "CSS",
".html": "HTML", ".json": "JSON", ".md": "MD",
".ts": "TS", ".xml": "XML", ".yaml": "YAML",
".sql": "SQL", ".txt": "TXT", ".log": "LOG"
}
def generate_preview(self, file_path, output_dir):
"""Generate preview for a code file."""
ext = os.path.splitext(file_path)[1].lower()
lang = self.supported_extensions.get(ext, "TXT")
code = self.code_handler.load_code(file_path)
filename = os.path.basename(file_path)
output = os.path.join(output_dir, f"{filename}_preview.png")
return self.code_handler.generate_preview(code, lang, output)
def generate_thumbnail(self, file_path, output_dir, size=128):
"""Generate thumbnail for a code file."""
filename = os.path.basename(file_path)
output = os.path.join(output_dir, f"{filename}_thumb.png")
self.code_handler._do_generate_icon(file_path, output, size)
return output
from ObjDocumentCode import ObjDocumentCode
def generate_code_samples(code_snippets, output_dir):
"""Generate syntax-highlighted images for documentation."""
code = ObjDocumentCode()
for i, (snippet, language) in enumerate(code_snippets):
output = os.path.join(output_dir, f"sample_{i+1}.png")
code.generate_preview(snippet, language, output)
print(f"Generated {output}")
# Usage
snippets = [
("def hello():\n print('Hello')", "PY"),
("const x = 42;", "JS"),
("SELECT * FROM users;", "SQL"),
]
generate_code_samples(snippets, "/docs/images")
Error: Warning about missing DejaVu Sans Mono font
Solution:
Ubuntu/Debian:
sudo apt-get install fonts-dejavu
macOS:
brew install --cask font-dejavu
Verify fonts:
from matplotlib import font_manager
fonts = font_manager.findSystemFonts()
dejavu = [f for f in fonts if "DejaVu" in f]
print(dejavu)
Error: ModuleNotFoundError: No module named 'pygments'
Solution:
pip install pygments
Issue: Slow preview generation for large files
Solution:
# Reduce max_lines for faster processing
code = ObjDocumentCode()
code_text = code.load_code("/large_file.py", max_lines=15)
Issue: File with unknown extension gets HTML highlighting
Solution:
Explicitly specify language:
code = ObjDocumentCode()
code_text = code.load_code("/file.xyz")
# Manually specify language
code.generate_preview(code_text, "PY", "/output.png")
Issue: Weird characters in preview for non-UTF-8 files
Solution:
The module uses errors="replace" which replaces invalid UTF-8 bytes with �. To handle specific encodings:
# Read with specific encoding first
with open(file_path, 'r', encoding='latin-1') as f:
code_text = f.read()
# Then generate preview
code = ObjDocumentCode()
code.generate_preview(code_text, "PY", "/output.png")
ObjDocumentDelegate.py - Base class for document delegatesObjDocumentTools.py - Shared thumbnail utilitiesObjDocumentArchive.py - Archive file listing previewObjDocument.py - Main document handler that delegates to format-specific handlers