-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvimark.py
More file actions
81 lines (68 loc) · 2.76 KB
/
vimark.py
File metadata and controls
81 lines (68 loc) · 2.76 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
#!/usr/bin/env python3
import argparse
import os
import signal
import sys
from pathlib import Path
from subprocess import Popen, DEVNULL
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MarkReloadHandler(FileSystemEventHandler):
"""Watchdog handler to send SIGHUP to mark on file modification."""
def __init__(self, mark_pid):
self.mark_pid = mark_pid
def on_modified(self, event):
if not event.is_directory and event.src_path.endswith('.md') and self.mark_pid is not None:
try:
os.kill(self.mark_pid, signal.SIGHUP)
except ProcessLookupError:
pass
def main():
parser = argparse.ArgumentParser(description="Vimark: Integrated Markdown editor and live viewer.")
parser.add_argument("file", nargs="?", help="Path to the Markdown file (.md)")
args = parser.parse_args()
if not args.file:
parser.print_help()
sys.exit(1)
file_path = Path(args.file)
# Check if file has .md extension
if not file_path.suffix == '.md':
print(f"Error: '{file_path}' must be a .md file.", file=sys.stderr)
sys.exit(1)
# Create file if it doesn't exist
if not file_path.exists():
# Ensure parent directory exists
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.touch() # Create the file
print(f"Created new file: {file_path}")
# Step 3: Spawn mark as detached background process (non-blocking, no TTY)
# Use 'mark' entry point (pipx global script), not 'mark.py'
mark_proc = Popen([sys.executable, os.path.join(os.path.dirname(__file__), 'mark.py'), str(file_path)], stdout=DEVNULL, start_new_session=True)
if mark_proc.poll() is not None:
print("Warning: mark viewer unavailable (no display). Editing without preview.", file=sys.stderr)
mark_pid = None
else:
mark_pid = mark_proc.pid
# Step 4: Start file watcher thread for SIGHUP on modify
event_handler = MarkReloadHandler(mark_pid)
event_handler.observer = Observer() # For stop in handler
event_handler.observer.schedule(event_handler, path=str(file_path.parent), recursive=False)
event_handler.observer.start()
try:
# Step 2: Spawn and block on vim (foreground, inherits TTY)
vim_exit_code = os.system(f"vim {file_path}")
except KeyboardInterrupt:
pass
finally:
# Step 5: Stop watcher and kill mark
event_handler.observer.stop()
event_handler.observer.join()
if mark_pid is not None:
try:
os.killpg(mark_pid, signal.SIGKILL)
except ProcessLookupError:
pass
mark_proc.wait()
sys.exit(0)
if __name__ == "__main__":
main()