Skip to content

Instantly share code, notes, and snippets.

@jpic
Created April 2, 2025 15:34
Show Gist options
  • Save jpic/9545df57414a845e79781ea3ebef05ae to your computer and use it in GitHub Desktop.
Save jpic/9545df57414a845e79781ea3ebef05ae to your computer and use it in GitHub Desktop.
markdown2console.py
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
def render_markdown_to_console(markdown_text):
lines = markdown_text.split('\n')
in_code_block = False
current_language = None
code_buffer = []
for line in lines:
# Check for code block start/end
if line.strip().startswith('```'):
if not in_code_block:
# Start of code block
in_code_block = True
current_language = line.strip()[3:].strip() or 'text'
else:
# End of code block - process and print
in_code_block = False
code_content = '\n'.join(code_buffer)
if current_language != 'text':
try:
lexer = get_lexer_by_name(current_language)
formatted_code = highlight(code_content, lexer, TerminalFormatter())
print(formatted_code.rstrip())
except:
# Fallback to plain text if lexer not found
print(code_content)
else:
print(code_content)
code_buffer = []
current_language = None
continue
# Process lines based on context
if in_code_block:
code_buffer.append(line)
else:
# Print regular markdown text as-is
print(line)
# Example Markdown content
markdown_content = """
# Code Examples for Pygments Lexing
## Python
```python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment