-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmark.py
More file actions
176 lines (150 loc) · 5.84 KB
/
mark.py
File metadata and controls
176 lines (150 loc) · 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python3
import argparse
import signal
import sys
from pathlib import Path
from threading import Event
import os
import markdown
from PyQt6.QtCore import QTimer, pyqtSignal, pyqtSlot
from PyQt6.QtGui import QCloseEvent
from PyQt6.QtWebEngineCore import QWebEnginePage
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWidgets import QApplication, QMainWindow
# Markdown extensions for complete GFM support (tables, syntax highlighting, etc.)
EXTENSIONS = [
'markdown.extensions.tables',
'markdown.extensions.fenced_code',
'markdown.extensions.codehilite',
'pymdownx.highlight', # Better syntax highlighting
'pymdownx.superfences', # Nested code blocks
'pymdownx.inlinehilite', # Inline code highlighting
'markdown.extensions.md_in_html', # Markdown in HTML tags
'pymdownx.arithmatex', # Math support (optional)
'pymdownx.tasklist', # Task lists
'pymdownx.tilde', # Strikethrough
]
class MarkdownWebPage(QWebEnginePage):
"""Custom WebPage to handle reload signals."""
reload_signal = pyqtSignal()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.reload_signal.connect(self._reload_slot)
@pyqtSlot()
def _reload_slot(self):
"""Slot to trigger page reload."""
self.reload()
class MarkdownViewer(QMainWindow):
def __init__(self, file_path: Path, reload_event: Event, quit_event: Event):
super().__init__()
self.file_path = file_path
self.reload_event = reload_event
self.quit_event = quit_event
self.web_view = QWebEngineView()
self.page = MarkdownWebPage(self.web_view)
self.web_view.setPage(self.page)
# Set up timer to poll events (for signal responsiveness)
self.timer = QTimer()
self.timer.timeout.connect(self.check_events)
self.timer.start(100) # Poll every 100ms
self.setCentralWidget(self.web_view)
self.setWindowTitle(f"Render: {file_path.name}")
self.resize(800, 600)
# Initial load
self.load_markdown()
def load_markdown(self):
"""Convert Markdown to HTML and load into web view."""
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
md_text = f.read()
except IOError as e:
print(f"Error reading file: {e}", file=sys.stderr)
return
md = markdown.Markdown(extensions=EXTENSIONS)
html = md.convert(md_text)
# Wrap in basic HTML for styling (light theme)
full_html = f"""
<!DOCTYPE html>
<html>
<head>
<title>{self.file_path.name}</title>
<style>
body {{
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: white;
color: black;
}}
h1 {{ color: #333; }}
h2 {{ color: #555; }}
h3 {{ color: #666; }}
code {{ background: #f4f4f4; padding: 2px 4px; }}
pre {{ background: #f4f4f4; padding: 10px; overflow: auto; }}
table {{ border-collapse: collapse; width: 100%; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
th {{ background-color: #f2f2f2; }}
blockquote {{ border-left: 4px solid #ccc; margin: 0; padding-left: 16px; color: #666; }}
ul, ol {{ padding-left: 20px; }}
li {{ margin-bottom: 4px; }}
</style>
</head>
<body>
{html}
</body>
</html>
"""
self.web_view.setHtml(full_html)
print(f"Markdown loaded and rendered for: {self.file_path}")
def check_events(self):
"""Poll for reload or quit events."""
if self.reload_event.is_set():
print("Reload triggered!") # Debug print
self.reload_event.clear()
self.load_markdown()
if self.quit_event.is_set():
print("Quit triggered!") # Debug print
self.quit_event.clear()
self.close()
def closeEvent(self, event: QCloseEvent):
"""Handle window close."""
self.quit_event.set()
event.accept()
def signal_handler(signum, frame):
global reload_event, quit_event
if signum == signal.SIGINT: # Ctrl+C
print("SIGINT received!") # Debug print
quit_event.set()
elif signum == signal.SIGHUP: # Reload
print("SIGHUP received!") # Debug print
reload_event.set()
def main():
parser = argparse.ArgumentParser(description="Graphical Markdown renderer with live reload.")
parser.add_argument("file", help="Path to the Markdown file")
args = parser.parse_args()
if not os.environ.get("DISPLAY") and os.environ.get("QT_QPA_PLATFORM") != "offscreen":
if os.path.exists("/tmp/.X11-unix/X0"):
import subprocess as _sp
_r = _sp.run(["xauth", "list"], capture_output=True, text=True)
if "unix:0" in _r.stdout:
os.environ["DISPLAY"] = ":0"
if not os.environ.get("DISPLAY"):
sys.exit(0)
file_path = Path(args.file)
if not file_path.exists():
print(f"Error: File '{file_path}' not found.", file=sys.stderr)
sys.exit(1)
# Global events for signals
reload_event = Event()
quit_event = Event()
# Register signal handlers
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGHUP, signal_handler)
# Set up Qt app
app = QApplication(sys.argv)
viewer = MarkdownViewer(file_path, reload_event, quit_event)
viewer.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()