texwatch 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- texwatch/__init__.py +3 -0
- texwatch/cli.py +240 -0
- texwatch/compiler.py +207 -0
- texwatch/deps.py +102 -0
- texwatch/lock.py +90 -0
- texwatch/logging_util.py +35 -0
- texwatch/revise.py +123 -0
- texwatch/ui.py +77 -0
- texwatch/watcher.py +142 -0
- texwatch-1.0.0.dist-info/METADATA +240 -0
- texwatch-1.0.0.dist-info/RECORD +15 -0
- texwatch-1.0.0.dist-info/WHEEL +5 -0
- texwatch-1.0.0.dist-info/entry_points.txt +2 -0
- texwatch-1.0.0.dist-info/licenses/LICENSE +21 -0
- texwatch-1.0.0.dist-info/top_level.txt +1 -0
texwatch/__init__.py
ADDED
texwatch/cli.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""texwatch CLI entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .compiler import Compiler
|
|
12
|
+
from .lock import DirLock, LockError
|
|
13
|
+
from .logging_util import setup_logging
|
|
14
|
+
from .revise import check_latexdiff, make_diff
|
|
15
|
+
from .ui import banner, error, info, success, warn
|
|
16
|
+
from .watcher import DebouncedWatcher
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_arg_parser() -> argparse.ArgumentParser:
|
|
20
|
+
p = argparse.ArgumentParser(
|
|
21
|
+
prog="texwatch",
|
|
22
|
+
description=(
|
|
23
|
+
"Watch a .tex file, recompile with pdflatex on change, and refresh "
|
|
24
|
+
"the PDF — like a terminal-based Overleaf."
|
|
25
|
+
),
|
|
26
|
+
)
|
|
27
|
+
p.add_argument("tex", nargs="?", type=Path, help="the .tex file to watch")
|
|
28
|
+
p.add_argument("--out", type=Path, default=None,
|
|
29
|
+
help="build directory (default: ./build next to the tex file)")
|
|
30
|
+
p.add_argument("--engine", default="pdflatex",
|
|
31
|
+
choices=["pdflatex", "xelatex", "lualatex"],
|
|
32
|
+
help="LaTeX engine (default: pdflatex)")
|
|
33
|
+
p.add_argument("--debounce", type=int, default=500, metavar="MS",
|
|
34
|
+
help="quiet period after last change before compiling (default: 500)")
|
|
35
|
+
p.add_argument("--timeout", type=float, default=30.0, metavar="S",
|
|
36
|
+
help="kill hung compiles after this many seconds (default: 30)")
|
|
37
|
+
p.add_argument("--once", action="store_true",
|
|
38
|
+
help="compile once and exit (no watching)")
|
|
39
|
+
p.add_argument("--clean", action="store_true",
|
|
40
|
+
help="remove the build directory and exit")
|
|
41
|
+
p.add_argument("--quiet", action="store_true",
|
|
42
|
+
help="only show errors")
|
|
43
|
+
p.add_argument("--verbose", action="store_true",
|
|
44
|
+
help="debug output to stderr (for bug reports)")
|
|
45
|
+
p.add_argument("--log-file", type=Path, default=None, metavar="FILE",
|
|
46
|
+
help="write a rotating debug log to FILE")
|
|
47
|
+
p.add_argument("--poll", action="store_true",
|
|
48
|
+
help="use polling watcher (reliable on network mounts: "
|
|
49
|
+
"NFS/SMB — slower, but no inotify needed)")
|
|
50
|
+
p.add_argument("--revise", type=Path, default=None, metavar="OLD.tex",
|
|
51
|
+
help="revision mode: diff against this baseline and also "
|
|
52
|
+
"produce a highlighted <stem>-diff.pdf")
|
|
53
|
+
p.add_argument("--diff-type", default="UNDERLINE", metavar="T",
|
|
54
|
+
help="latexdiff markup type: UNDERLINE, CFONT, CHANGEBAR, "
|
|
55
|
+
"BOLD, PDFCOMMENT… (default: UNDERLINE)")
|
|
56
|
+
p.add_argument("--highlight", choices=["yellow", "classic"], default="yellow",
|
|
57
|
+
help="revision markup style: yellow = yellow highlight for "
|
|
58
|
+
"additions + red strikethrough deletions (default); "
|
|
59
|
+
"classic = latexdiff's native style")
|
|
60
|
+
p.add_argument("--diff-out", default=None, metavar="NAME",
|
|
61
|
+
help="basename for diff outputs (default: <stem>-diff)")
|
|
62
|
+
p.add_argument("--no-diff", dest="make_diff", action="store_false", default=True,
|
|
63
|
+
help="in revision mode, suspend diffing (clean PDF only)")
|
|
64
|
+
p.add_argument("--version", action="version", version=f"texwatch {__version__}")
|
|
65
|
+
return p
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _build_pipeline(
|
|
69
|
+
tex: Path,
|
|
70
|
+
compiler: Compiler,
|
|
71
|
+
baseline: Path | None,
|
|
72
|
+
diff_type: str,
|
|
73
|
+
diff_name: str | None,
|
|
74
|
+
make_diff_enabled: bool = True,
|
|
75
|
+
highlight: str = "yellow",
|
|
76
|
+
) -> int:
|
|
77
|
+
"""Compile tex (clean) and, in revision mode, the highlighted diff.
|
|
78
|
+
|
|
79
|
+
Returns 0 if the clean compile succeeded, 1 otherwise. Diff failure is
|
|
80
|
+
non-fatal and reported separately.
|
|
81
|
+
"""
|
|
82
|
+
result = compiler.compile(tex)
|
|
83
|
+
if not result.ok:
|
|
84
|
+
error("compile failed")
|
|
85
|
+
for e in result.errors:
|
|
86
|
+
print(f" {e}")
|
|
87
|
+
if baseline is not None:
|
|
88
|
+
warn("revision diff skipped (clean compile failed)")
|
|
89
|
+
return 1
|
|
90
|
+
|
|
91
|
+
success(f"built {result.pdf_path} ({result.duration:.1f}s)")
|
|
92
|
+
status = 0
|
|
93
|
+
|
|
94
|
+
if baseline is not None and make_diff_enabled:
|
|
95
|
+
out_dir = compiler.out_dir or tex.parent
|
|
96
|
+
name = diff_name or f"{tex.stem}-diff"
|
|
97
|
+
diff_tex = out_dir / f"{name}.tex"
|
|
98
|
+
d = make_diff(baseline, tex, diff_tex, diff_type=diff_type,
|
|
99
|
+
highlight=(highlight == "yellow"))
|
|
100
|
+
if not d.ok:
|
|
101
|
+
warn(f"diff generation failed (keeping last good {name}.pdf)")
|
|
102
|
+
if d.error_msg:
|
|
103
|
+
for line in d.error_msg.splitlines()[:5]:
|
|
104
|
+
print(f" {line}")
|
|
105
|
+
status = 0 # diff failure never fails the overall build
|
|
106
|
+
else:
|
|
107
|
+
# compile with cwd = source dir so relative figure paths resolve,
|
|
108
|
+
# while outputs still land in the build dir
|
|
109
|
+
dresult = compiler.compile(diff_tex, cwd=tex.parent)
|
|
110
|
+
if dresult.ok:
|
|
111
|
+
success(
|
|
112
|
+
f"built {dresult.pdf_path} "
|
|
113
|
+
f"({dresult.passes} pass{'es' if dresult.passes > 1 else ''}, "
|
|
114
|
+
f"{dresult.duration:.1f}s)"
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
warn(f"diff compile failed (keeping last good {name}.pdf)")
|
|
118
|
+
for e in dresult.errors[:5]:
|
|
119
|
+
print(f" {e}")
|
|
120
|
+
return status
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def main(argv: list[str] | None = None) -> int:
|
|
124
|
+
args = build_arg_parser().parse_args(argv)
|
|
125
|
+
|
|
126
|
+
setup_logging(verbose=args.verbose, log_file=args.log_file)
|
|
127
|
+
|
|
128
|
+
if args.clean:
|
|
129
|
+
return _clean(args)
|
|
130
|
+
|
|
131
|
+
if args.tex is None:
|
|
132
|
+
build_arg_parser().error("the .tex file is required (or use --clean)")
|
|
133
|
+
|
|
134
|
+
tex = args.tex.resolve()
|
|
135
|
+
if tex.suffix != ".tex":
|
|
136
|
+
warn(f"'{tex.name}' does not end in .tex — continuing anyway")
|
|
137
|
+
if not tex.is_file():
|
|
138
|
+
error(f"file not found: {tex}")
|
|
139
|
+
return 2
|
|
140
|
+
|
|
141
|
+
out_dir = (args.out or tex.parent / "build").resolve()
|
|
142
|
+
compiler = Compiler(engine=args.engine, out_dir=out_dir, timeout=args.timeout)
|
|
143
|
+
|
|
144
|
+
missing = compiler.check_engine()
|
|
145
|
+
if missing:
|
|
146
|
+
error(missing)
|
|
147
|
+
return 2
|
|
148
|
+
|
|
149
|
+
if args.clean:
|
|
150
|
+
return _clean(args)
|
|
151
|
+
|
|
152
|
+
# --- revision mode setup -------------------------------------------------
|
|
153
|
+
baseline: Path | None = None
|
|
154
|
+
if args.revise is not None:
|
|
155
|
+
baseline = args.revise.resolve()
|
|
156
|
+
if not baseline.is_file():
|
|
157
|
+
error(f"baseline file not found: {baseline}")
|
|
158
|
+
return 2
|
|
159
|
+
missing_ld = check_latexdiff()
|
|
160
|
+
if missing_ld:
|
|
161
|
+
warn(f"{missing_ld} revision mode disabled; clean watching continues.")
|
|
162
|
+
baseline = None
|
|
163
|
+
|
|
164
|
+
if args.once:
|
|
165
|
+
return _build_pipeline(
|
|
166
|
+
tex, compiler, baseline, args.diff_type, args.diff_out, args.make_diff,
|
|
167
|
+
highlight=args.highlight,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# --- watch mode ---------------------------------------------------------
|
|
171
|
+
if args.quiet:
|
|
172
|
+
import texwatch.ui as ui
|
|
173
|
+
ui.success = lambda m: None # type: ignore[assignment]
|
|
174
|
+
ui.info = lambda m: None # type: ignore[assignment]
|
|
175
|
+
ui.dim = lambda m: None # type: ignore[assignment]
|
|
176
|
+
|
|
177
|
+
# single instance per build dir
|
|
178
|
+
try:
|
|
179
|
+
lock = DirLock(out_dir)
|
|
180
|
+
lock.acquire()
|
|
181
|
+
except LockError as e:
|
|
182
|
+
error(str(e))
|
|
183
|
+
return 3
|
|
184
|
+
|
|
185
|
+
watcher = DebouncedWatcher(tex, compiler, debounce_ms=args.debounce, poll=args.poll)
|
|
186
|
+
|
|
187
|
+
from .deps import parse_deps
|
|
188
|
+
revise_desc = f"diffing against {baseline.name} ({args.diff_type})" if baseline else "off"
|
|
189
|
+
banner(str(tex), str(out_dir), args.engine,
|
|
190
|
+
len(parse_deps(tex)), args.debounce, revise_desc)
|
|
191
|
+
|
|
192
|
+
watcher.start()
|
|
193
|
+
|
|
194
|
+
# hook: full pipeline (clean + diff) on each rebuild
|
|
195
|
+
def run_compile_with_open() -> None:
|
|
196
|
+
_build_pipeline(
|
|
197
|
+
tex, compiler, baseline, args.diff_type, args.diff_out, args.make_diff,
|
|
198
|
+
highlight=args.highlight,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
watcher._run_compile = run_compile_with_open # noqa: SLF001
|
|
202
|
+
|
|
203
|
+
info("watching for changes…")
|
|
204
|
+
try:
|
|
205
|
+
watcher.wait()
|
|
206
|
+
except Exception: # crash safety: clean report, never a raw traceback
|
|
207
|
+
error("texwatch hit an unexpected error — please file an issue with "
|
|
208
|
+
"the output of `texwatch --log-file tw.log ...`")
|
|
209
|
+
import traceback
|
|
210
|
+
traceback.print_exc()
|
|
211
|
+
return 4
|
|
212
|
+
finally:
|
|
213
|
+
watcher.stop()
|
|
214
|
+
with _suppress(LockError, OSError):
|
|
215
|
+
lock.release()
|
|
216
|
+
info("stopped.")
|
|
217
|
+
return 0
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _suppress(*exc: type[BaseException]):
|
|
221
|
+
import contextlib
|
|
222
|
+
return contextlib.suppress(*exc)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _clean(args: argparse.Namespace) -> int:
|
|
226
|
+
if args.tex is None:
|
|
227
|
+
error("--clean requires a tex file (to locate the build dir)")
|
|
228
|
+
return 2
|
|
229
|
+
tex = args.tex.resolve()
|
|
230
|
+
out_dir = (args.out or tex.parent / "build").resolve()
|
|
231
|
+
if out_dir.is_dir():
|
|
232
|
+
shutil.rmtree(out_dir)
|
|
233
|
+
success(f"removed {out_dir}")
|
|
234
|
+
else:
|
|
235
|
+
info(f"nothing to clean at {out_dir}")
|
|
236
|
+
return 0
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
if __name__ == "__main__":
|
|
240
|
+
sys.exit(main())
|
texwatch/compiler.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Compile LaTeX via pdflatex/xelatex/lualatex with multi-pass support and log parsing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
_PASS_MAX = 3
|
|
16
|
+
|
|
17
|
+
# Platform-specific TeX discovery, checked after PATH.
|
|
18
|
+
_TEX_DIRS: list[Path] = []
|
|
19
|
+
if sys.platform == "darwin":
|
|
20
|
+
_TEX_DIRS = [Path("/Library/TeX/texbin"), Path("/usr/local/bin")]
|
|
21
|
+
elif sys.platform == "win32":
|
|
22
|
+
_TEX_DIRS = [
|
|
23
|
+
Path(os.path.expandvars(r"%LOCALAPPDATA%\Programs\MiKTeX\miktex\bin\x64")),
|
|
24
|
+
Path(os.path.expandvars(r"%APPDATA%\MiKTeX\miktex\bin\x64")),
|
|
25
|
+
Path(r"C:\Program Files\MiKTeX\miktex\bin\x64"),
|
|
26
|
+
]
|
|
27
|
+
# TeX Live year dirs
|
|
28
|
+
for root in (Path(r"C:\texlive"),):
|
|
29
|
+
if root.is_dir():
|
|
30
|
+
_TEX_DIRS.extend(sorted(root.glob(r"*\bin\windows"), reverse=True))
|
|
31
|
+
else: # linux & other unix
|
|
32
|
+
_TEX_DIRS = [Path("/usr/local/bin")]
|
|
33
|
+
tl = Path("/usr/local/texlive")
|
|
34
|
+
if tl.is_dir():
|
|
35
|
+
_TEX_DIRS.extend(
|
|
36
|
+
sorted(tl.glob("*/bin/x86_64-linux"), reverse=True)
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def find_engine(engine: str) -> str | None:
|
|
41
|
+
"""Locate *engine* on PATH or in known TeX install dirs. Returns path or None."""
|
|
42
|
+
found = shutil.which(engine)
|
|
43
|
+
if found:
|
|
44
|
+
return found
|
|
45
|
+
for d in _TEX_DIRS:
|
|
46
|
+
cand = d / engine
|
|
47
|
+
if cand.is_file():
|
|
48
|
+
return str(cand)
|
|
49
|
+
# Windows: engines are .exe
|
|
50
|
+
cand_exe = d / f"{engine}.exe"
|
|
51
|
+
if cand_exe.is_file():
|
|
52
|
+
return str(cand_exe)
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_INSTALL_HINTS = {
|
|
57
|
+
"darwin": (
|
|
58
|
+
"Install MacTeX: https://www.tug.org/mactex/ "
|
|
59
|
+
"(or `brew install --cask mactex-no-gui`)"
|
|
60
|
+
),
|
|
61
|
+
"linux": (
|
|
62
|
+
"Install TeX Live: `sudo apt install texlive-latex-extra "
|
|
63
|
+
"texlive-fonts-recommended` (Debian/Ubuntu)"
|
|
64
|
+
),
|
|
65
|
+
"win32": (
|
|
66
|
+
"Install MiKTeX: https://miktex.org/download "
|
|
67
|
+
"(adds engines to PATH optionally)"
|
|
68
|
+
),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
_RERUN_HINTS = (
|
|
72
|
+
"Rerun to get cross-references",
|
|
73
|
+
"Rerun to get citations",
|
|
74
|
+
"Label(s) may have changed",
|
|
75
|
+
"Please rerun LaTeX",
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
_ERROR_RE = re.compile(
|
|
79
|
+
r"^!.*$|^.*:\d+:\s.*", re.MULTILINE
|
|
80
|
+
)
|
|
81
|
+
_ERROR_LINE_RE = re.compile(
|
|
82
|
+
r"(?m)^(.+?\.(?:tex|sty|cls)):(\d+):\s*(.*)$|^(!\s*.*)$"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class CompileResult:
|
|
88
|
+
ok: bool
|
|
89
|
+
pdf_path: Path | None
|
|
90
|
+
passes: int
|
|
91
|
+
duration: float
|
|
92
|
+
errors: list[str] = field(default_factory=list)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Compiler:
|
|
96
|
+
def __init__(
|
|
97
|
+
self,
|
|
98
|
+
engine: str = "pdflatex",
|
|
99
|
+
out_dir: Path | None = None,
|
|
100
|
+
timeout: float = 30.0,
|
|
101
|
+
):
|
|
102
|
+
self.engine = engine
|
|
103
|
+
self.engine_path: str | None = None
|
|
104
|
+
self.out_dir = out_dir
|
|
105
|
+
self.timeout = timeout
|
|
106
|
+
|
|
107
|
+
def check_engine(self) -> str | None:
|
|
108
|
+
"""Resolve the engine binary; return an error message if unavailable."""
|
|
109
|
+
path = find_engine(self.engine)
|
|
110
|
+
if path is None:
|
|
111
|
+
hint = _INSTALL_HINTS.get(sys.platform, _INSTALL_HINTS["linux"])
|
|
112
|
+
return (
|
|
113
|
+
f"'{self.engine}' not found on PATH or in known TeX locations. "
|
|
114
|
+
f"{hint} Or pass --engine."
|
|
115
|
+
)
|
|
116
|
+
self.engine_path = path
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
def _run_once(
|
|
120
|
+
self, tex_file: Path, cwd: Path | None = None
|
|
121
|
+
) -> subprocess.CompletedProcess:
|
|
122
|
+
cmd = [
|
|
123
|
+
self.engine_path or self.engine,
|
|
124
|
+
"-interaction=nonstopmode",
|
|
125
|
+
"-halt-on-error",
|
|
126
|
+
"-file-line-error",
|
|
127
|
+
f"-output-directory={self.out_dir or tex_file.parent}",
|
|
128
|
+
str(tex_file) if cwd is not None else tex_file.name,
|
|
129
|
+
]
|
|
130
|
+
return subprocess.run(
|
|
131
|
+
cmd,
|
|
132
|
+
cwd=cwd or tex_file.parent,
|
|
133
|
+
capture_output=True,
|
|
134
|
+
text=True,
|
|
135
|
+
timeout=self.timeout,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def compile(self, tex_file: Path, cwd: Path | None = None) -> CompileResult:
|
|
139
|
+
tex_file = tex_file.resolve()
|
|
140
|
+
if self.out_dir is not None:
|
|
141
|
+
self.out_dir.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
|
|
143
|
+
start = time.monotonic()
|
|
144
|
+
errors: list[str] = []
|
|
145
|
+
passes = 0
|
|
146
|
+
pdf_path = None
|
|
147
|
+
|
|
148
|
+
for _ in range(_PASS_MAX):
|
|
149
|
+
passes += 1
|
|
150
|
+
try:
|
|
151
|
+
proc = self._run_once(tex_file, cwd=cwd)
|
|
152
|
+
except subprocess.TimeoutExpired:
|
|
153
|
+
return CompileResult(
|
|
154
|
+
False, None, passes, time.monotonic() - start,
|
|
155
|
+
[f"compile timed out after {self.timeout}s"],
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
log_text = proc.stdout or ""
|
|
159
|
+
log_file = (self.out_dir or tex_file.parent) / (
|
|
160
|
+
tex_file.stem + ".log"
|
|
161
|
+
)
|
|
162
|
+
if log_file.is_file():
|
|
163
|
+
with contextlib.suppress(OSError):
|
|
164
|
+
log_text += "\n" + log_file.read_text(
|
|
165
|
+
encoding="utf-8", errors="replace"
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
candidate = (self.out_dir or tex_file.parent) / (
|
|
169
|
+
tex_file.stem + ".pdf"
|
|
170
|
+
)
|
|
171
|
+
pdf_path = candidate if candidate.is_file() else None
|
|
172
|
+
|
|
173
|
+
if proc.returncode != 0:
|
|
174
|
+
errors = parse_errors(log_text)
|
|
175
|
+
return CompileResult(
|
|
176
|
+
False, pdf_path, passes, time.monotonic() - start, errors
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
if not any(h in log_text for h in _RERUN_HINTS):
|
|
180
|
+
break # references stable; done
|
|
181
|
+
|
|
182
|
+
return CompileResult(
|
|
183
|
+
True, pdf_path, passes, time.monotonic() - start, errors
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def parse_errors(log_text: str) -> list[str]:
|
|
188
|
+
"""Extract file:line + message pairs from a LaTeX log."""
|
|
189
|
+
errors: list[str] = []
|
|
190
|
+
for match in _ERROR_LINE_RE.finditer(log_text):
|
|
191
|
+
file, line, msg, bang = match.groups()
|
|
192
|
+
if bang:
|
|
193
|
+
errors.append(bang.strip())
|
|
194
|
+
else:
|
|
195
|
+
errors.append(f"{file}:{line}: {msg.strip()}")
|
|
196
|
+
if not errors:
|
|
197
|
+
# fall back to any line starting with "!"
|
|
198
|
+
for m in re.finditer(r"(?m)^(!.+)$", log_text):
|
|
199
|
+
errors.append(m.group(1).strip())
|
|
200
|
+
# de-duplicate, preserve order, skip noisy repeats
|
|
201
|
+
seen: set[str] = set()
|
|
202
|
+
unique: list[str] = []
|
|
203
|
+
for e in errors:
|
|
204
|
+
if e not in seen:
|
|
205
|
+
seen.add(e)
|
|
206
|
+
unique.append(e)
|
|
207
|
+
return unique[:10]
|
texwatch/deps.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Parse a .tex file for \\input/\\include/graphics/bibliography dependencies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
# Commands that pull in other files: (regex, default extension, kind)
|
|
9
|
+
_PATTERNS = [
|
|
10
|
+
# \input{file} or \input file (plain \input without braces)
|
|
11
|
+
(
|
|
12
|
+
re.compile(r"\\input\{([^}]+)\}|\\input\s+([^\s{%\\]+)"),
|
|
13
|
+
".tex",
|
|
14
|
+
"tex",
|
|
15
|
+
),
|
|
16
|
+
(re.compile(r"\\include\{([^}]+)\}"), ".tex", "tex"),
|
|
17
|
+
(
|
|
18
|
+
re.compile(
|
|
19
|
+
r"\\includegraphics(?:\s*\[[^\]]*\])?\s*\{([^}]+)\}"
|
|
20
|
+
),
|
|
21
|
+
"",
|
|
22
|
+
"graphic",
|
|
23
|
+
),
|
|
24
|
+
(re.compile(r"\\bibliography\{([^}]+)\}"), ".bib", "bib"),
|
|
25
|
+
(re.compile(r"\\lstinputlisting(?:\s*\[[^\]]*\])?\s*\{([^}]+)\}"), "", "other"),
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
# TeX-style comment: everything after an unescaped %
|
|
29
|
+
_COMMENT = re.compile(r"(?<!\\)%.*")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _strip_comments(text: str) -> str:
|
|
33
|
+
return _COMMENT.sub("", text)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _resolve(base_dir: Path, name: str, default_ext: str) -> Path | None:
|
|
37
|
+
"""Resolve a dependency path, trying with and without the default extension."""
|
|
38
|
+
name = name.strip()
|
|
39
|
+
if not name:
|
|
40
|
+
return None
|
|
41
|
+
candidate = Path(name)
|
|
42
|
+
if not candidate.is_absolute():
|
|
43
|
+
candidate = base_dir / candidate
|
|
44
|
+
candidates = [candidate] if default_ext == "" else [candidate]
|
|
45
|
+
if default_ext and candidate.suffix != default_ext:
|
|
46
|
+
candidates.append(Path(str(candidate) + default_ext))
|
|
47
|
+
for c in candidates:
|
|
48
|
+
if c.is_file():
|
|
49
|
+
try:
|
|
50
|
+
return c.resolve()
|
|
51
|
+
except OSError:
|
|
52
|
+
return None
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def parse_deps(
|
|
57
|
+
tex_file: Path, _visited: set[Path] | None = None
|
|
58
|
+
) -> list[Path]:
|
|
59
|
+
"""Recursively find all files referenced by *tex_file* (cycle-safe).
|
|
60
|
+
|
|
61
|
+
Returns resolved Paths, excluding *tex_file* itself.
|
|
62
|
+
"""
|
|
63
|
+
if _visited is None:
|
|
64
|
+
_visited = set()
|
|
65
|
+
tex_file = tex_file.resolve()
|
|
66
|
+
if tex_file in _visited:
|
|
67
|
+
return []
|
|
68
|
+
_visited.add(tex_file)
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
# UTF-8 with fallback: Windows files are often cp1252/latin-1
|
|
72
|
+
try:
|
|
73
|
+
text = tex_file.read_text(encoding="utf-8")
|
|
74
|
+
except UnicodeDecodeError:
|
|
75
|
+
text = tex_file.read_text(encoding="cp1252", errors="replace")
|
|
76
|
+
except OSError:
|
|
77
|
+
return []
|
|
78
|
+
|
|
79
|
+
text = _strip_comments(text)
|
|
80
|
+
base_dir = tex_file.parent
|
|
81
|
+
deps: list[Path] = []
|
|
82
|
+
|
|
83
|
+
for pattern, default_ext, kind in _PATTERNS:
|
|
84
|
+
for match in pattern.finditer(text):
|
|
85
|
+
raw = next((g for g in match.groups() if g), None)
|
|
86
|
+
if raw is None:
|
|
87
|
+
continue
|
|
88
|
+
resolved = _resolve(base_dir, raw, default_ext)
|
|
89
|
+
if resolved is None or resolved == tex_file:
|
|
90
|
+
continue
|
|
91
|
+
deps.append(resolved)
|
|
92
|
+
if kind == "tex":
|
|
93
|
+
deps.extend(parse_deps(resolved, _visited))
|
|
94
|
+
|
|
95
|
+
# de-duplicate, preserve order
|
|
96
|
+
seen: set[Path] = set()
|
|
97
|
+
unique: list[Path] = []
|
|
98
|
+
for d in deps:
|
|
99
|
+
if d not in seen:
|
|
100
|
+
seen.add(d)
|
|
101
|
+
unique.append(d)
|
|
102
|
+
return unique
|
texwatch/lock.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Single-instance lock per build directory (best-effort, crash-safe)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
_LOCK_NAME = ".texwatch.lock"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LockError(RuntimeError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DirLock:
|
|
17
|
+
"""Advisory lock so two texwatch instances don't fight over a build dir.
|
|
18
|
+
|
|
19
|
+
Uses O_EXCL create on all platforms; a stale lock (dead PID) is stolen.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, directory: Path):
|
|
23
|
+
self.path = directory / _LOCK_NAME
|
|
24
|
+
self._fd: int | None = None
|
|
25
|
+
|
|
26
|
+
def acquire(self) -> None:
|
|
27
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
try:
|
|
29
|
+
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
30
|
+
except FileExistsError:
|
|
31
|
+
if self._stale():
|
|
32
|
+
with _suppress(OSError):
|
|
33
|
+
self.path.unlink()
|
|
34
|
+
try:
|
|
35
|
+
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
36
|
+
except FileExistsError:
|
|
37
|
+
raise LockError(
|
|
38
|
+
f"another texwatch instance appears to be running "
|
|
39
|
+
f"(lock: {self.path}). Delete the lock file if that's wrong."
|
|
40
|
+
) from None
|
|
41
|
+
else:
|
|
42
|
+
raise LockError(
|
|
43
|
+
f"another texwatch instance appears to be running "
|
|
44
|
+
f"(lock: {self.path}). Delete the lock file if that's wrong."
|
|
45
|
+
) from None
|
|
46
|
+
os.write(fd, f"{os.getpid()}\n".encode())
|
|
47
|
+
self._fd = fd
|
|
48
|
+
|
|
49
|
+
def _stale(self) -> bool:
|
|
50
|
+
"""A lock is stale if its PID no longer exists."""
|
|
51
|
+
try:
|
|
52
|
+
pid = int(self.path.read_text().strip())
|
|
53
|
+
except (OSError, ValueError):
|
|
54
|
+
return True # unreadable/corrupt -> treat as stale
|
|
55
|
+
if sys.platform == "win32":
|
|
56
|
+
# no os.kill(pid, 0) on Windows; assume stale after check via tasklist
|
|
57
|
+
import subprocess
|
|
58
|
+
out = subprocess.run(
|
|
59
|
+
["tasklist", "/FI", f"PID eq {pid}"],
|
|
60
|
+
capture_output=True, text=True,
|
|
61
|
+
)
|
|
62
|
+
return str(pid) not in out.stdout
|
|
63
|
+
try:
|
|
64
|
+
os.kill(pid, 0)
|
|
65
|
+
return False
|
|
66
|
+
except ProcessLookupError:
|
|
67
|
+
return True
|
|
68
|
+
except PermissionError:
|
|
69
|
+
return False # exists, not ours
|
|
70
|
+
|
|
71
|
+
def release(self) -> None:
|
|
72
|
+
if self._fd is not None:
|
|
73
|
+
with _suppress(OSError):
|
|
74
|
+
os.close(self._fd)
|
|
75
|
+
with _suppress(OSError):
|
|
76
|
+
self.path.unlink()
|
|
77
|
+
self._fd = None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _suppress:
|
|
81
|
+
"""Minimal contextlib.suppress to keep imports light here."""
|
|
82
|
+
|
|
83
|
+
def __init__(self, *exc: type[BaseException]):
|
|
84
|
+
self._exc = exc
|
|
85
|
+
|
|
86
|
+
def __enter__(self):
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
def __exit__(self, et, ev, tb):
|
|
90
|
+
return et is not None and issubclass(et, self._exc)
|
texwatch/logging_util.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Structured logging: --verbose console + optional rotating log file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import logging.handlers
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
LOGGER = logging.getLogger("texwatch")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def setup_logging(verbose: bool = False, log_file: Path | None = None) -> None:
|
|
14
|
+
LOGGER.setLevel(logging.DEBUG)
|
|
15
|
+
LOGGER.handlers.clear()
|
|
16
|
+
|
|
17
|
+
console = logging.StreamHandler(sys.stderr)
|
|
18
|
+
console.setLevel(logging.DEBUG if verbose else logging.WARNING)
|
|
19
|
+
console.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
|
|
20
|
+
LOGGER.addHandler(console)
|
|
21
|
+
|
|
22
|
+
if log_file is not None:
|
|
23
|
+
log_file.parent.mkdir(parents=True, exist_ok=True)
|
|
24
|
+
fh = logging.handlers.RotatingFileHandler(
|
|
25
|
+
log_file, maxBytes=1_000_000, backupCount=2, encoding="utf-8"
|
|
26
|
+
)
|
|
27
|
+
fh.setLevel(logging.DEBUG)
|
|
28
|
+
fh.setFormatter(
|
|
29
|
+
logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
30
|
+
)
|
|
31
|
+
LOGGER.addHandler(fh)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_logger(name: str = "texwatch") -> logging.Logger:
|
|
35
|
+
return logging.getLogger(name)
|
texwatch/revise.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Revision mode: latexdiff-based change highlighting against a baseline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
_DIFF_TIMEOUT = 30.0
|
|
11
|
+
|
|
12
|
+
# Injected after latexdiff's preamble: additions highlighted yellow, deletions
|
|
13
|
+
# red strikethrough. Uses only xcolor (\colorbox) — no soul dependency.
|
|
14
|
+
# DIFdel is defined \long by latexdiff; keep it that way so multi-line deletions
|
|
15
|
+
# (e.g. a `_1` on its own line inside math) don't break.
|
|
16
|
+
_PREAMBLE_INJECT = r"""
|
|
17
|
+
%--- texwatch revision highlighting -------------------
|
|
18
|
+
\definecolor{tw-yellow}{RGB}{255,255,120}
|
|
19
|
+
% math-safe yellow highlight: \colorbox breaks inside math mode, so make
|
|
20
|
+
% DIFadd behave like latexdiff's native \uwave — fall back to plain blue
|
|
21
|
+
% when inside math (\DIFmathadd used in text stays highlighted).
|
|
22
|
+
\long\def\DIFadd#1{{\colorbox{tw-yellow}{#1}}}
|
|
23
|
+
\long\def\DIFdel#1{{\color{red}\sout{#1}}}
|
|
24
|
+
%--- end texwatch revision highlighting ---------------
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class DiffResult:
|
|
30
|
+
ok: bool
|
|
31
|
+
diff_tex: Path | None
|
|
32
|
+
error_msg: str | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def check_latexdiff() -> str | None:
|
|
36
|
+
"""Return error message if latexdiff is unavailable."""
|
|
37
|
+
from .compiler import _INSTALL_HINTS, find_engine
|
|
38
|
+
|
|
39
|
+
if find_engine("latexdiff") is None:
|
|
40
|
+
hint = _INSTALL_HINTS.get(sys.platform, _INSTALL_HINTS["linux"])
|
|
41
|
+
return (
|
|
42
|
+
f"latexdiff not found. It ships with most TeX distributions; "
|
|
43
|
+
f"otherwise: `brew install latexdiff` (macOS) or see your distro. {hint}"
|
|
44
|
+
)
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _inject(body: str, snippet: str) -> str:
|
|
49
|
+
"""Insert *snippet* after latexdiff's preamble marker (or before \\begin{document})."""
|
|
50
|
+
marker = "%DIF PREAMBLE EXTENSION ADDED BY LATEXDIFF"
|
|
51
|
+
if marker in body:
|
|
52
|
+
# insert at the END of the DIF preamble block, right before \begin{document}
|
|
53
|
+
idx = body.find(r"\begin{document}")
|
|
54
|
+
if idx != -1:
|
|
55
|
+
return body[:idx] + snippet + "\n" + body[idx:]
|
|
56
|
+
return body.replace(
|
|
57
|
+
r"\begin{document}", snippet + "\n\\begin{document}", 1
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def make_diff(
|
|
62
|
+
baseline: Path,
|
|
63
|
+
revised: Path,
|
|
64
|
+
out_tex: Path,
|
|
65
|
+
diff_type: str = "UNDERLINE",
|
|
66
|
+
flatten: bool = True,
|
|
67
|
+
highlight: bool = True,
|
|
68
|
+
) -> DiffResult:
|
|
69
|
+
"""Run latexdiff baseline vs revised, writing markup tex to *out_tex*.
|
|
70
|
+
|
|
71
|
+
Returns DiffResult; never raises. Output tex is written to the build dir
|
|
72
|
+
so relative figure paths resolve the same as the main compile.
|
|
73
|
+
"""
|
|
74
|
+
cmd = [
|
|
75
|
+
"latexdiff",
|
|
76
|
+
f"--type={diff_type}",
|
|
77
|
+
"--encoding=utf8",
|
|
78
|
+
]
|
|
79
|
+
# use the discovered latexdiff path if it's off-PATH (Windows TeX Live, etc.)
|
|
80
|
+
from .compiler import find_engine
|
|
81
|
+
ld = find_engine("latexdiff")
|
|
82
|
+
if ld:
|
|
83
|
+
cmd[0] = ld
|
|
84
|
+
if flatten:
|
|
85
|
+
cmd.append("--flatten")
|
|
86
|
+
cmd += [str(baseline), str(revised)]
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
proc = subprocess.run(
|
|
90
|
+
cmd,
|
|
91
|
+
cwd=str(revised.parent),
|
|
92
|
+
capture_output=True,
|
|
93
|
+
text=True,
|
|
94
|
+
timeout=_DIFF_TIMEOUT,
|
|
95
|
+
)
|
|
96
|
+
except subprocess.TimeoutExpired:
|
|
97
|
+
return DiffResult(False, None, f"latexdiff timed out after {_DIFF_TIMEOUT}s")
|
|
98
|
+
except FileNotFoundError:
|
|
99
|
+
return DiffResult(False, None, "latexdiff not found")
|
|
100
|
+
|
|
101
|
+
if proc.returncode != 0 or not proc.stdout.strip():
|
|
102
|
+
msg = (proc.stderr or proc.stdout or "unknown latexdiff error").strip()
|
|
103
|
+
return DiffResult(False, None, msg[:500])
|
|
104
|
+
|
|
105
|
+
body = proc.stdout
|
|
106
|
+
if highlight:
|
|
107
|
+
# latexdiff emits inline-math changes as \DIFdelbegin \DIFdel{_1
|
|
108
|
+
# }\DIFdelend \DIFaddbegin \DIFadd{_2 }\DIFaddend — a \colorbox around
|
|
109
|
+
# "_2" inside $...$ breaks ("Missing $ inserted"). Protect math-mode
|
|
110
|
+
# fragments: yellow highlight in text, plain red/blue in math.
|
|
111
|
+
_MATH_GUARD = r"""
|
|
112
|
+
\makeatletter
|
|
113
|
+
\let\tw@orig@DIFadd\DIFadd
|
|
114
|
+
\let\tw@orig@DIFdel\DIFdel
|
|
115
|
+
\renewcommand{\DIFadd}[1]{\ifmmode{\color{blue}#1}\else\tw@orig@DIFadd{#1}\fi}
|
|
116
|
+
\renewcommand{\DIFdel}[1]{\ifmmode{\color{red}#1}\else\tw@orig@DIFdel{#1}\fi}
|
|
117
|
+
\makeatother
|
|
118
|
+
"""
|
|
119
|
+
body = _inject(body, _PREAMBLE_INJECT + _MATH_GUARD)
|
|
120
|
+
|
|
121
|
+
out_tex.parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
out_tex.write_text(body, encoding="utf-8")
|
|
123
|
+
return DiffResult(True, out_tex, None)
|
texwatch/ui.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Small ANSI terminal UI helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
_RESET = "\033[0m"
|
|
8
|
+
_BOLD = "\033[1m"
|
|
9
|
+
_GREEN = "\033[32m"
|
|
10
|
+
_RED = "\033[31m"
|
|
11
|
+
_YELLOW = "\033[33m"
|
|
12
|
+
_CYAN = "\033[36m"
|
|
13
|
+
_DIM = "\033[2m"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _no_color() -> bool:
|
|
17
|
+
return not sys.stdout.isatty()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def info(msg: str) -> None:
|
|
21
|
+
if _no_color():
|
|
22
|
+
print(msg, flush=True)
|
|
23
|
+
else:
|
|
24
|
+
print(f"{_CYAN}ℹ{_RESET} {msg}", flush=True)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def success(msg: str) -> None:
|
|
28
|
+
if _no_color():
|
|
29
|
+
print(msg, flush=True)
|
|
30
|
+
else:
|
|
31
|
+
print(f"{_GREEN}{_BOLD}✓{_RESET} {msg}", flush=True)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def warn(msg: str) -> None:
|
|
35
|
+
if _no_color():
|
|
36
|
+
print(msg, flush=True)
|
|
37
|
+
else:
|
|
38
|
+
print(f"{_YELLOW}⚠{_RESET} {msg}", flush=True)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def error(msg: str) -> None:
|
|
42
|
+
if _no_color():
|
|
43
|
+
print(msg, flush=True)
|
|
44
|
+
else:
|
|
45
|
+
print(f"{_RED}{_BOLD}✗{_RESET} {msg}", flush=True)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def dim(msg: str) -> None:
|
|
49
|
+
if _no_color():
|
|
50
|
+
print(msg, flush=True)
|
|
51
|
+
else:
|
|
52
|
+
print(f"{_DIM}{msg}{_RESET}", flush=True)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def error_block(errors: list[str], pdf_kept: bool) -> None:
|
|
56
|
+
error("compile failed")
|
|
57
|
+
for e in errors:
|
|
58
|
+
if _no_color():
|
|
59
|
+
print(f" {e}", flush=True)
|
|
60
|
+
else:
|
|
61
|
+
print(f" {_RED}{e}{_RESET}", flush=True)
|
|
62
|
+
if pdf_kept:
|
|
63
|
+
dim(" (keeping last successful PDF)")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def banner(tex: str, out: str, engine: str, deps: int, debounce_ms: int,
|
|
67
|
+
revise: str = "off") -> None:
|
|
68
|
+
print(f"""
|
|
69
|
+
{_BOLD}texwatch{_RESET} — watching {tex}
|
|
70
|
+
engine : {engine}
|
|
71
|
+
output : {out}
|
|
72
|
+
deps : {deps} file(s) also watched
|
|
73
|
+
debounce : {debounce_ms} ms
|
|
74
|
+
revise : {revise}
|
|
75
|
+
|
|
76
|
+
{_DIM}Ctrl-C to stop.{_RESET}
|
|
77
|
+
""", flush=True)
|
texwatch/watcher.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Watch .tex + dependencies with debounce and single deferred recompile."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from watchdog.events import FileSystemEvent, FileSystemEventHandler
|
|
10
|
+
from watchdog.observers import Observer
|
|
11
|
+
from watchdog.observers.api import BaseObserver
|
|
12
|
+
|
|
13
|
+
from .compiler import Compiler
|
|
14
|
+
from .deps import parse_deps
|
|
15
|
+
from .ui import dim, error_block, success
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _Handler(FileSystemEventHandler):
|
|
19
|
+
def __init__(self, callback, watched: set[Path]):
|
|
20
|
+
self.callback = callback
|
|
21
|
+
self.watched = watched
|
|
22
|
+
|
|
23
|
+
def _relevant(self, path: str) -> bool:
|
|
24
|
+
p = Path(path).resolve()
|
|
25
|
+
return p in self.watched and p.suffix in {
|
|
26
|
+
".tex", ".bib", ".sty", ".cls", ".png", ".jpg", ".jpeg", ".pdf", ".eps"
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
def on_any_event(self, event: FileSystemEvent) -> None:
|
|
30
|
+
if event.is_directory:
|
|
31
|
+
return
|
|
32
|
+
dest = getattr(event, "dest_path", None)
|
|
33
|
+
paths = [event.src_path] + ([dest] if dest else [])
|
|
34
|
+
if any(self._relevant(p) for p in paths if p):
|
|
35
|
+
self.callback()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DebouncedWatcher:
|
|
39
|
+
"""Watches a set of files; fires *action* once the tree is quiet."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
tex_file: Path,
|
|
44
|
+
compiler: Compiler,
|
|
45
|
+
debounce_ms: int = 500,
|
|
46
|
+
poll: bool = False,
|
|
47
|
+
):
|
|
48
|
+
self.tex_file = tex_file
|
|
49
|
+
self.compiler = compiler
|
|
50
|
+
self.debounce = debounce_ms / 1000.0
|
|
51
|
+
|
|
52
|
+
if poll:
|
|
53
|
+
# reliable on NFS/SMB/network mounts where inotify events don't propagate
|
|
54
|
+
from watchdog.observers.polling import PollingObserver
|
|
55
|
+
self._observer: BaseObserver = PollingObserver(timeout=1.0)
|
|
56
|
+
else:
|
|
57
|
+
self._observer = Observer()
|
|
58
|
+
self._timer: threading.Timer | None = None
|
|
59
|
+
self._lock = threading.Lock()
|
|
60
|
+
|
|
61
|
+
self._compile_lock = threading.Lock()
|
|
62
|
+
self._dirty = False
|
|
63
|
+
self._stop = False
|
|
64
|
+
|
|
65
|
+
self._deps: list[Path] = []
|
|
66
|
+
self._watched: set[Path] = set()
|
|
67
|
+
self._rescan_deps()
|
|
68
|
+
|
|
69
|
+
# --- dependency management -------------------------------------------
|
|
70
|
+
|
|
71
|
+
def _rescan_deps(self) -> None:
|
|
72
|
+
deps = parse_deps(self.tex_file)
|
|
73
|
+
self._deps = deps
|
|
74
|
+
self._watched = {self.tex_file} | set(deps)
|
|
75
|
+
|
|
76
|
+
# --- compile loop ------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
def _request_compile(self) -> None:
|
|
79
|
+
with self._lock:
|
|
80
|
+
if self._timer is not None:
|
|
81
|
+
self._timer.cancel()
|
|
82
|
+
self._timer = threading.Timer(self.debounce, self._fire)
|
|
83
|
+
self._timer.daemon = True
|
|
84
|
+
self._timer.start()
|
|
85
|
+
|
|
86
|
+
def _fire(self) -> None:
|
|
87
|
+
with self._lock:
|
|
88
|
+
self._timer = None
|
|
89
|
+
if not self._compile_lock.acquire(blocking=False):
|
|
90
|
+
# a compile is running — mark dirty, it will re-run after
|
|
91
|
+
with self._lock:
|
|
92
|
+
self._dirty = True
|
|
93
|
+
dim("change detected during compile — will recompile after")
|
|
94
|
+
return
|
|
95
|
+
try:
|
|
96
|
+
self._run_compile()
|
|
97
|
+
while True:
|
|
98
|
+
with self._lock:
|
|
99
|
+
if not self._dirty or self._stop:
|
|
100
|
+
self._dirty = False
|
|
101
|
+
break
|
|
102
|
+
self._dirty = False
|
|
103
|
+
self._run_compile()
|
|
104
|
+
finally:
|
|
105
|
+
self._compile_lock.release()
|
|
106
|
+
|
|
107
|
+
def _run_compile(self) -> None:
|
|
108
|
+
result = self.compiler.compile(self.tex_file)
|
|
109
|
+
# refresh deps after each compile (new \input may have appeared)
|
|
110
|
+
self._rescan_deps()
|
|
111
|
+
if result.ok:
|
|
112
|
+
success(
|
|
113
|
+
f"rebuilt {result.pdf_path} "
|
|
114
|
+
f"({result.passes} pass{'es' if result.passes > 1 else ''}, "
|
|
115
|
+
f"{result.duration:.1f}s)"
|
|
116
|
+
)
|
|
117
|
+
else:
|
|
118
|
+
error_block(result.errors, pdf_kept=result.pdf_path is not None)
|
|
119
|
+
|
|
120
|
+
# --- lifecycle ---------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
def start(self) -> None:
|
|
123
|
+
for d in {self.tex_file.parent} | {p.parent for p in self._deps}:
|
|
124
|
+
handler = _Handler(self._request_compile, self._watched)
|
|
125
|
+
self._observer.schedule(handler, str(d), recursive=False)
|
|
126
|
+
self._observer.daemon = True
|
|
127
|
+
self._observer.start()
|
|
128
|
+
|
|
129
|
+
def stop(self) -> None:
|
|
130
|
+
with self._lock:
|
|
131
|
+
self._stop = True
|
|
132
|
+
if self._timer is not None:
|
|
133
|
+
self._timer.cancel()
|
|
134
|
+
self._observer.stop()
|
|
135
|
+
self._observer.join(timeout=2)
|
|
136
|
+
|
|
137
|
+
def wait(self) -> None:
|
|
138
|
+
try:
|
|
139
|
+
while self._observer.is_alive():
|
|
140
|
+
time.sleep(0.5)
|
|
141
|
+
except KeyboardInterrupt:
|
|
142
|
+
pass
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: texwatch
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Terminal-based Overleaf-like LaTeX watcher: recompiles pdflatex on file change and refreshes the PDF.
|
|
5
|
+
Author: Arif
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/arif/texwatch
|
|
8
|
+
Keywords: latex,pdflatex,watch,overleaf,pdf
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: watchdog>=3.0
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
18
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
19
|
+
Requires-Dist: mypy>=1.11; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# texwatch
|
|
23
|
+
|
|
24
|
+
[](https://github.com/YOUR_USERNAME/texwatch/actions/workflows/ci.yml)
|
|
25
|
+
[](https://pypi.org/project/texwatch/)
|
|
26
|
+
[](https://pypi.org/project/texwatch/)
|
|
27
|
+
|
|
28
|
+
**A terminal-based Overleaf for LaTeX.** Watch a `.tex` file, recompile
|
|
29
|
+
automatically when it changes — while you edit in your own editor and view the
|
|
30
|
+
PDF in whatever viewer you like. On top of that, **revision mode** produces a
|
|
31
|
+
journal-style "marked-up copy" (yellow highlights for additions, red
|
|
32
|
+
strikethrough for deletions) that updates live as you revise a manuscript.
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
$ texwatch manuscript/main.tex --revise manuscript/submitted-v1.tex
|
|
36
|
+
|
|
37
|
+
texwatch — watching manuscript/main.tex
|
|
38
|
+
engine : pdflatex
|
|
39
|
+
output : manuscript/build
|
|
40
|
+
deps : 3 file(s) also watched
|
|
41
|
+
debounce : 500 ms
|
|
42
|
+
revise : diffing against submitted-v1.tex (UNDERLINE)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Why texwatch?
|
|
48
|
+
|
|
49
|
+
- **Zero-config watch**: edit anywhere (VS Code, vim, TeXShop, Notepad++),
|
|
50
|
+
texwatch rebuilds ~0.5 s after you save. Open the PDF in any viewer —
|
|
51
|
+
auto-refreshing ones (Skim, SumatraPDF, Evince, Zathura) will pick up each
|
|
52
|
+
rebuild live.
|
|
53
|
+
- **Dependency-aware**: edits to `\input`/`\include`/`\includegraphics`/
|
|
54
|
+
`\bibliography` files also trigger rebuilds.
|
|
55
|
+
- **Revision mode**: an auto-regenerating highlighted "diff PDF" for
|
|
56
|
+
journal resubmissions — no more manually marking changes.
|
|
57
|
+
- **Cross-platform**: macOS, Linux, Windows. Detects your TeX distribution
|
|
58
|
+
automatically.
|
|
59
|
+
- **Respectful of your machine**: debounced, queued compiles; artifacts in
|
|
60
|
+
`build/`; your last good PDF is never destroyed by a broken compile.
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Install
|
|
65
|
+
|
|
66
|
+
Requires **Python 3.9+** and a TeX distribution (MacTeX / TeX Live / MiKTeX).
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
# any platform, isolated install (recommended)
|
|
70
|
+
pipx install texwatch
|
|
71
|
+
# or
|
|
72
|
+
uv tool install texwatch
|
|
73
|
+
# or
|
|
74
|
+
pip install --user texwatch
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Install TeX if needed:
|
|
78
|
+
|
|
79
|
+
| OS | Command |
|
|
80
|
+
|---|---|
|
|
81
|
+
| macOS | `brew install --cask mactex-no-gui` |
|
|
82
|
+
| Debian/Ubuntu | `sudo apt install texlive-latex-extra texlive-fonts-recommended` |
|
|
83
|
+
| Windows | [MiKTeX](https://miktex.org/download) |
|
|
84
|
+
|
|
85
|
+
For **revision mode**, latexdiff is required (ships with full TeX Live/MacTeX;
|
|
86
|
+
MiKTeX may prompt to install it).
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Quick start
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
texwatch main.tex # watch & compile
|
|
94
|
+
texwatch main.tex --revise v1.tex # + live highlighted revision copy
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Try the bundled demo:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
git clone https://github.com/YOUR_USERNAME/texwatch && cd texwatch/examples
|
|
101
|
+
texwatch main.tex --revise v1.tex
|
|
102
|
+
# now edit main.tex or sections/intro.tex in another terminal; watch
|
|
103
|
+
# build/main.pdf and build/main-diff.pdf update — open them in any viewer
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## The manual
|
|
109
|
+
|
|
110
|
+
### Concepts
|
|
111
|
+
|
|
112
|
+
```
|
|
113
|
+
texwatch REVISED.tex --revise REFERENCE.tex
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
| Argument | Role |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `REVISED.tex` (positional) | The file you are editing. Watched and compiled. |
|
|
119
|
+
| `REFERENCE.tex` (`--revise`) | The frozen original (e.g. the submitted version). Used only as the "before" for latexdiff; never modified or compiled. |
|
|
120
|
+
|
|
121
|
+
Every time you save (in the revised file **or any of its dependencies**):
|
|
122
|
+
|
|
123
|
+
1. A **debounce** timer waits for 500 ms of quiet (resets on each save).
|
|
124
|
+
2. The clean PDF is compiled (up to 3 passes, resolving cross-references).
|
|
125
|
+
3. In revision mode, `latexdiff --flatten` computes the diff and the marked-up
|
|
126
|
+
PDF is compiled right after. Diff failures never block the clean PDF.
|
|
127
|
+
|
|
128
|
+
### Revision mode
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
texwatch main.tex --revise submitted-v1.tex
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
produces:
|
|
135
|
+
|
|
136
|
+
| Output | Content |
|
|
137
|
+
|---|---|
|
|
138
|
+
| `build/main.pdf` | your clean revised paper |
|
|
139
|
+
| `build/main-diff.pdf` | changes marked: **yellow highlight = added**, **red strikethrough = deleted** (blue text inside math) |
|
|
140
|
+
|
|
141
|
+
Options:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
--diff-type CFONT # latexdiff markup style (UNDERLINE, CFONT, CHANGEBAR, BOLD…)
|
|
145
|
+
--diff-out mydiff # custom output basename
|
|
146
|
+
--highlight classic # latexdiff's native markup instead of yellow
|
|
147
|
+
--no-diff # suspend diffing, keep watching (escape hatch)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Tips from the trenches:
|
|
151
|
+
|
|
152
|
+
- Keep the baseline file **frozen** — it's your reference snapshot.
|
|
153
|
+
- If a diff compile fails on exotic packages (algorithm2e, minted, …), use
|
|
154
|
+
`--no-diff` to keep working, or try `--diff-type PDFCOMMENT`.
|
|
155
|
+
- Network drives (NFS/SMB, HPC home dirs) may not deliver file events:
|
|
156
|
+
add `--poll`.
|
|
157
|
+
|
|
158
|
+
### All options
|
|
159
|
+
|
|
160
|
+
```text
|
|
161
|
+
Positional:
|
|
162
|
+
tex the .tex file to watch
|
|
163
|
+
|
|
164
|
+
Build:
|
|
165
|
+
--out DIR build directory (default: ./build next to the tex file)
|
|
166
|
+
--engine ENGINE pdflatex | xelatex | lualatex (default: pdflatex)
|
|
167
|
+
--timeout S kill hung compiles after S seconds (default: 30)
|
|
168
|
+
|
|
169
|
+
Watching:
|
|
170
|
+
--debounce MS quiet period before compiling (default: 500)
|
|
171
|
+
--poll use polling (for NFS/SMB/network mounts)
|
|
172
|
+
--once compile once and exit
|
|
173
|
+
--clean remove the build directory and exit
|
|
174
|
+
|
|
175
|
+
Revision:
|
|
176
|
+
--revise OLD.tex enable revision mode against this baseline
|
|
177
|
+
--diff-type T latexdiff markup type (default: UNDERLINE)
|
|
178
|
+
--diff-out NAME basename for diff outputs (default: <stem>-diff)
|
|
179
|
+
--highlight STYLE yellow (default) or classic
|
|
180
|
+
--no-diff suspend diffing; clean PDF only
|
|
181
|
+
|
|
182
|
+
Output:
|
|
183
|
+
--quiet only show errors
|
|
184
|
+
--verbose debug output on stderr
|
|
185
|
+
|
|
186
|
+
Diagnostics:
|
|
187
|
+
--log-file FILE rotating debug log (attach to bug reports)
|
|
188
|
+
--version, --help
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### Viewing the PDF
|
|
192
|
+
|
|
193
|
+
texwatch deliberately does **not** open or manage a PDF viewer — you open
|
|
194
|
+
`build/main.pdf` in whatever you prefer. Viewers that auto-reload on file
|
|
195
|
+
change give the full Overleaf-like experience:
|
|
196
|
+
|
|
197
|
+
| OS | Auto-reloading viewers |
|
|
198
|
+
|---|---|
|
|
199
|
+
| macOS | Skim |
|
|
200
|
+
| Linux | Evince, Okular, Zathura, qpdfview |
|
|
201
|
+
| Windows | SumatraPDF (doesn't lock the file, unlike Acrobat/Edge) |
|
|
202
|
+
|
|
203
|
+
### Config discovery
|
|
204
|
+
|
|
205
|
+
texwatch finds TeX automatically: `PATH`, then known locations
|
|
206
|
+
(`/Library/TeX/texbin` on macOS; `C:\texlive\*\bin\windows` and MiKTeX dirs on
|
|
207
|
+
Windows; `/usr/local/texlive/*/bin/*` on Linux). Same for latexdiff.
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## Troubleshooting
|
|
212
|
+
|
|
213
|
+
| Symptom | Fix |
|
|
214
|
+
|---|---|
|
|
215
|
+
| `pdflatex not found` | Install TeX (table above) or add its bin dir to PATH |
|
|
216
|
+
| `another texwatch instance appears to be running` | Another watcher holds the build dir. Close it, or delete `build/.texwatch.lock` |
|
|
217
|
+
| Nothing happens when I save on a network drive | Use `--poll` |
|
|
218
|
+
| PDF doesn't refresh in my viewer | Use an auto-reloading viewer (table above); Acrobat/Edge on Windows lock the file |
|
|
219
|
+
| Diff PDF doesn't rebuild but clean does | latexdiff hiccup — see the warning line; try `--no-diff` or another `--diff-type` |
|
|
220
|
+
| Weird characters in the diff | Ensure UTF-8 sources; texwatch falls back to cp1252 automatically |
|
|
221
|
+
| Something else broke | `texwatch ... --log-file tw.log --verbose` and attach `tw.log` to an issue |
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
## Development
|
|
226
|
+
|
|
227
|
+
```bash
|
|
228
|
+
git clone https://github.com/YOUR_USERNAME/texwatch && cd texwatch
|
|
229
|
+
python -m venv .venv && source .venv/bin/activate
|
|
230
|
+
pip install -e ".[dev]"
|
|
231
|
+
pytest # unit + real-pdflatex integration tests
|
|
232
|
+
ruff check src tests
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Releases: push a tag `v1.0.0` — CI builds the wheel/sdist and publishes to
|
|
236
|
+
PyPI via trusted publishing.
|
|
237
|
+
|
|
238
|
+
## License
|
|
239
|
+
|
|
240
|
+
MIT
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
texwatch/__init__.py,sha256=PP1Y_gzvx_Gw_FoJnY7-sR1xQRn-7rwS0RewTkGnuGI,96
|
|
2
|
+
texwatch/cli.py,sha256=yf7fkvdtVapNrR9ZSwcu-iyibMHbpikMJLBsZAXGQ48,9023
|
|
3
|
+
texwatch/compiler.py,sha256=xi1D3udvydWnwksGU5IMZEMupbL70XqBqydgLO8w1bo,6333
|
|
4
|
+
texwatch/deps.py,sha256=gyW5kGFvIslE01eJbBnT0GGcNBQrPcSzLDW2mkiznw8,3070
|
|
5
|
+
texwatch/lock.py,sha256=tzetxGW02yLpUAFrl8CYHHh6T7FYo2gqgSjrPwhDZLQ,2876
|
|
6
|
+
texwatch/logging_util.py,sha256=O9GZoKu416AB_qSXIzndFTI4iNZcqxbmuWN-VqLDVHc,1102
|
|
7
|
+
texwatch/revise.py,sha256=0TpxPjQskqPO22JxK5Dn2nC6t-HPr-uK_RNU7LXXLlQ,4300
|
|
8
|
+
texwatch/ui.py,sha256=eiUC_hX1UDD0OyAIuyKo1ORcTM_AzcmluhxFsOaTa8s,1693
|
|
9
|
+
texwatch/watcher.py,sha256=DIFqmH7YtwiKNzQqdTJc2gaXJPj02cqMH4WDm-6QVJw,4700
|
|
10
|
+
texwatch-1.0.0.dist-info/licenses/LICENSE,sha256=FudYiBj8tP6xsnBou_QPRQcsdnf3noYa24BkQR9k45s,1078
|
|
11
|
+
texwatch-1.0.0.dist-info/METADATA,sha256=pHU3ui0KnZCJGw2GbmpRml2qmMvc7Lg2p086WEpq_Qg,8078
|
|
12
|
+
texwatch-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
texwatch-1.0.0.dist-info/entry_points.txt,sha256=tE8GRTtvN_6Srq-weOYY4wuTXsqqUqnbB9oEDrdTEpA,47
|
|
14
|
+
texwatch-1.0.0.dist-info/top_level.txt,sha256=YKGfIYHZWnoIMaJDgmcuCm4dTDZ43mISn6Mh_02bxL0,9
|
|
15
|
+
texwatch-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 texwatch contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
texwatch
|