course-index 0.1.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.
- course_index/VERSION.txt +1 -0
- course_index/__info__.py +18 -0
- course_index/__init__.py +6 -0
- course_index/__main__.py +104 -0
- course_index/common.py +106 -0
- course_index/compiler.py +178 -0
- course_index/course.py +93 -0
- course_index/gui/__init__.py +3 -0
- course_index/gui/app.py +1183 -0
- course_index/gui/dialogs.py +773 -0
- course_index/gui/widgets.py +383 -0
- course_index/idx.py +865 -0
- course_index/latex.py +216 -0
- course_index/preview.py +56 -0
- course_index/skeleton.idx +46 -0
- course_index/template/data.tex +4 -0
- course_index/template/lib/android.png +0 -0
- course_index/template/lib/app.png +0 -0
- course_index/template/lib/aws.png +0 -0
- course_index/template/lib/azure.png +0 -0
- course_index/template/lib/book.png +0 -0
- course_index/template/lib/cc-by-sa.png +0 -0
- course_index/template/lib/cc-by.png +0 -0
- course_index/template/lib/cc.png +0 -0
- course_index/template/lib/cloud.png +0 -0
- course_index/template/lib/cross-platform.png +0 -0
- course_index/template/lib/dollar.png +0 -0
- course_index/template/lib/dotnet.png +0 -0
- course_index/template/lib/executive.png +0 -0
- course_index/template/lib/file.png +0 -0
- course_index/template/lib/go.png +0 -0
- course_index/template/lib/group.png +0 -0
- course_index/template/lib/individual.png +0 -0
- course_index/template/lib/k8s.png +0 -0
- course_index/template/lib/linux.png +0 -0
- course_index/template/lib/mac.png +0 -0
- course_index/template/lib/malware.png +0 -0
- course_index/template/lib/note.png +0 -0
- course_index/template/lib/option.png +0 -0
- course_index/template/lib/perl.png +0 -0
- course_index/template/lib/portable.png +0 -0
- course_index/template/lib/powershell.png +0 -0
- course_index/template/lib/python.png +0 -0
- course_index/template/lib/question.png +0 -0
- course_index/template/lib/ruby.png +0 -0
- course_index/template/lib/script.png +0 -0
- course_index/template/lib/solaris.png +0 -0
- course_index/template/lib/std.ist +11 -0
- course_index/template/lib/tool.png +0 -0
- course_index/template/lib/tool_blue.png +0 -0
- course_index/template/lib/tool_red.png +0 -0
- course_index/template/lib/tuto.png +0 -0
- course_index/template/lib/warning.png +0 -0
- course_index/template/lib/web.png +0 -0
- course_index/template/lib/windows.png +0 -0
- course_index/template/main.tex +110 -0
- course_index/tui/__init__.py +3 -0
- course_index/tui/app.py +1022 -0
- course_index/tui/app.tcss +221 -0
- course_index/tui/screens.py +727 -0
- course_index/tui/widgets.py +160 -0
- course_index-0.1.0.dist-info/METADATA +775 -0
- course_index-0.1.0.dist-info/RECORD +67 -0
- course_index-0.1.0.dist-info/WHEEL +5 -0
- course_index-0.1.0.dist-info/entry_points.txt +2 -0
- course_index-0.1.0.dist-info/licenses/LICENSE +674 -0
- course_index-0.1.0.dist-info/top_level.txt +1 -0
course_index/VERSION.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
0.1.0
|
course_index/__info__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""Course Index package information.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
import os
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
__y = str(datetime.now().year)
|
|
9
|
+
__s = "2026"
|
|
10
|
+
|
|
11
|
+
__author__ = "Alexandre D'Hondt"
|
|
12
|
+
__copyright__ = "© {} A. D'Hondt".format([__y, __s + "-" + __y][__y != __s])
|
|
13
|
+
__email__ = "alexandre.dhondt@gmail.com"
|
|
14
|
+
__license__ = "GPLv3 (https://www.gnu.org/licenses/gpl-3.0.fr.html)"
|
|
15
|
+
__source__ = "https://github.com/academic-templates/course-index"
|
|
16
|
+
|
|
17
|
+
with open(os.path.join(os.path.dirname(__file__), "VERSION.txt")) as f:
|
|
18
|
+
__version__ = f.read().strip()
|
course_index/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""Course Index: a TUI for editing the index of the LaTeX course index template and compiling it to PDF."""
|
|
3
|
+
from .__info__ import __author__, __copyright__, __email__, __license__, __source__, __version__ # noqa: F401
|
|
4
|
+
from .compiler import BuildResult, compile_pdf, init_project # noqa: F401
|
|
5
|
+
from .course import CourseInfo, data_file_for # noqa: F401
|
|
6
|
+
from .idx import Document, Entry, Level, Problem, Raw # noqa: F401
|
course_index/__main__.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""Command-line entry point: `course-index [FILE.idx]`."""
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .__info__ import __source__, __version__
|
|
9
|
+
from .compiler import compile_pdf, init_project, open_file, template_dir
|
|
10
|
+
from .idx import Document
|
|
11
|
+
from .latex import known_commands
|
|
12
|
+
|
|
13
|
+
EXAMPLES = """examples:
|
|
14
|
+
course-index edit main.idx in the current folder (created if missing)
|
|
15
|
+
course-index sec504.idx edit another index
|
|
16
|
+
course-index sec504.idx --tui edit it in the terminal instead of a window
|
|
17
|
+
course-index --init mycourse/ copy the template (main.tex, data.tex, lib/) and start a new index there
|
|
18
|
+
course-index sec504.idx --pdf compile sec504.pdf without opening the editor
|
|
19
|
+
course-index sec504.idx --check list the problems of the index
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _parser():
|
|
24
|
+
p = argparse.ArgumentParser(prog="course-index", formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
25
|
+
description="Edit a course index (LaTeX course index template) and compile it to PDF.",
|
|
26
|
+
epilog=EXAMPLES + f"\nsource: {__source__}")
|
|
27
|
+
p.add_argument("path", nargs="?", default="main.idx",
|
|
28
|
+
help="index file, or folder holding main.idx (default: ./main.idx)")
|
|
29
|
+
g = p.add_mutually_exclusive_group()
|
|
30
|
+
g.add_argument("--pdf", action="store_true", help="compile the PDF and exit")
|
|
31
|
+
g.add_argument("--check", action="store_true", help="check the index and exit (exit code 1 on errors)")
|
|
32
|
+
p.add_argument("--init", action="store_true", help="copy the template files next to the index first")
|
|
33
|
+
p.add_argument("-o", "--output", help="PDF path for --pdf (default: the index path with .pdf)")
|
|
34
|
+
p.add_argument("--open", action="store_true", help="open the PDF after --pdf")
|
|
35
|
+
p.add_argument("--no-viewer", action="store_true", help="do not open the PDF after compiling from the editor")
|
|
36
|
+
p.add_argument("--tui", action="store_true", help="use the terminal user interface instead of the window")
|
|
37
|
+
p.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
|
|
38
|
+
return p
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _resolve(arg):
|
|
42
|
+
"""Index file of the given argument: a folder (existing, ending with a separator or without extension) means its
|
|
43
|
+
main.idx."""
|
|
44
|
+
path = Path(arg)
|
|
45
|
+
if path.is_dir() or arg.endswith(("/", "\\")) or path.suffix == "" and not path.exists():
|
|
46
|
+
path = path / "main.idx"
|
|
47
|
+
return path
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def has_display():
|
|
51
|
+
"""Whether a window can be opened (on Linux and BSD, an X11 or Wayland session is required)."""
|
|
52
|
+
if sys.platform in ("win32", "darwin") or os.environ.get("QT_QPA_PLATFORM"):
|
|
53
|
+
return True
|
|
54
|
+
return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def check(path):
|
|
58
|
+
doc = Document.load(path)
|
|
59
|
+
tex = template_dir(path) / "main.tex"
|
|
60
|
+
problems = doc.check(known_commands(tex.read_text(encoding="utf-8", errors="replace")))
|
|
61
|
+
lines = doc.line_numbers()
|
|
62
|
+
for p in problems:
|
|
63
|
+
print(f"{path}:{lines[p.index]}: {p.severity}: {p.message}")
|
|
64
|
+
n_err = sum(p.severity == "error" for p in problems)
|
|
65
|
+
print(f"{len(problems)} problem(s), {n_err} error(s)", file=sys.stderr)
|
|
66
|
+
return 1 if n_err else 0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def main(argv=None):
|
|
70
|
+
args = _parser().parse_args(argv)
|
|
71
|
+
path = _resolve(args.path)
|
|
72
|
+
if args.init:
|
|
73
|
+
copied = init_project(path.parent)
|
|
74
|
+
print(f"Template copied to {path.parent.resolve()} ({len(copied)} new files)", file=sys.stderr)
|
|
75
|
+
if not path.exists():
|
|
76
|
+
from .common import SKELETON
|
|
77
|
+
path.write_text(SKELETON.read_text(encoding="utf-8"), encoding="utf-8")
|
|
78
|
+
if args.pdf or args.check:
|
|
79
|
+
if not path.exists():
|
|
80
|
+
print(f"{path}: no such file", file=sys.stderr)
|
|
81
|
+
return 2
|
|
82
|
+
if args.check:
|
|
83
|
+
return check(path)
|
|
84
|
+
result = compile_pdf(path, args.output)
|
|
85
|
+
for w in result.warnings:
|
|
86
|
+
print(f"warning: {w}", file=sys.stderr)
|
|
87
|
+
for e in result.errors:
|
|
88
|
+
print(f"error: {e}", file=sys.stderr)
|
|
89
|
+
print(result.summary, file=sys.stderr if not result.ok else sys.stdout)
|
|
90
|
+
if result.ok and args.open:
|
|
91
|
+
open_file(result.pdf)
|
|
92
|
+
return 0 if result.ok else 1
|
|
93
|
+
if not args.tui:
|
|
94
|
+
if has_display():
|
|
95
|
+
from .gui import run
|
|
96
|
+
return run(path, open_pdf=not args.no_viewer)
|
|
97
|
+
print("No display found: starting the terminal user interface", file=sys.stderr)
|
|
98
|
+
from .tui.app import IndexApp
|
|
99
|
+
IndexApp(path, open_pdf=not args.no_viewer).run()
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
if __name__ == "__main__":
|
|
104
|
+
sys.exit(main())
|
course_index/common.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""Helpers shared by the user interfaces (GUI and TUI): decorations of a level, kinds of lines, help text."""
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .latex import ICONS
|
|
7
|
+
|
|
8
|
+
__all__ = ["HELP", "KIND_MARKS", "MAX_LEVELS", "SKELETON", "join_decorations", "split_decorations"]
|
|
9
|
+
|
|
10
|
+
SKELETON = Path(__file__).parent / "skeleton.idx"
|
|
11
|
+
KIND_MARKS = {"spacer": ("␣", "blank line"), "pagebreak": ("⤓", "page break"), "xref": ("↪", None),
|
|
12
|
+
"hidden": ("◌", None)}
|
|
13
|
+
MAX_LEVELS = 4
|
|
14
|
+
_ICON_RE = re.compile(r"\s*\\(" + "|".join(sorted(ICONS, key=len, reverse=True)) + r")(?![A-Za-z])")
|
|
15
|
+
_RATE_RE = re.compile(r"\s*\\rate\{(\d+)\}")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def split_decorations(text):
|
|
19
|
+
"""Split a level text into (text without icons and rating, [icons], rating)."""
|
|
20
|
+
icons = _ICON_RE.findall(text)
|
|
21
|
+
m = _RATE_RE.search(text)
|
|
22
|
+
rating = int(m.group(1)) if m else 0
|
|
23
|
+
base = _RATE_RE.sub("", _ICON_RE.sub("", text)).rstrip()
|
|
24
|
+
return base, icons, rating
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def join_decorations(base, icons, rating):
|
|
28
|
+
text = base.rstrip()
|
|
29
|
+
if icons:
|
|
30
|
+
text += " " + "".join(f"\\{i}" for i in icons)
|
|
31
|
+
if rating:
|
|
32
|
+
text += f" \\rate{{{rating}}}"
|
|
33
|
+
return text
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
HELP = r"""
|
|
37
|
+
# Course Index — help
|
|
38
|
+
|
|
39
|
+
## Adding references (the quick-add bar)
|
|
40
|
+
|
|
41
|
+
1. Set the **book** (e.g. `1`, `2` or `W` for the workbook; it must exist, **F3** creates a new one) and the
|
|
42
|
+
**page** (`45` or a range `45-47`; not 0, and a range must end after it starts).
|
|
43
|
+
2. Type the **term** and press **Enter**. The book and page stay, ready for the next term.
|
|
44
|
+
|
|
45
|
+
- `Term!Sub-term` adds a sub-level (up to 3 levels).
|
|
46
|
+
- Suggestions of existing terms show while typing: **↑/↓** to choose, **Tab** to complete.
|
|
47
|
+
Completing an existing term keeps its exact key, so the pages merge on the same line.
|
|
48
|
+
- **Ctrl+↑ / Ctrl+↓** (or PageUp/PageDown) increment/decrement the page.
|
|
49
|
+
- Shortcuts: `` `nc` `` → `\texttt{nc}`, `**x**` → `\textbf{x}`, `*x*` → `\textit{x}`, `:linux:` → `\linux`.
|
|
50
|
+
`_ & % #` are escaped automatically.
|
|
51
|
+
|
|
52
|
+
The template's conventions are applied for you: `|book{N}` on the first page of a term in a book, a new
|
|
53
|
+
`term! ` line for each additional book, a sort key for terms starting with a command (`\texttt{.htaccess}` →
|
|
54
|
+
`Htaccess@\texttt{.htaccess}`), and the entry goes to its group (Topics/Categories) or its book's section.
|
|
55
|
+
|
|
56
|
+
## Entries table
|
|
57
|
+
|
|
58
|
+
Each section of the file is a block of lines, collapsed by default (▶, with its number of entries and a ⚠/✖ when it
|
|
59
|
+
hides a problem). Selecting an entry (after adding it, from the Problems or the Preview, ...) expands its section.
|
|
60
|
+
|
|
61
|
+
| Key | Action |
|
|
62
|
+
|---|---|
|
|
63
|
+
| → / ← | expand / collapse the section (also Enter, Space or a click on the caret of its header) |
|
|
64
|
+
| + / - | expand / collapse all the sections |
|
|
65
|
+
| Enter / e | edit the entry (structured fields synchronized with the raw line), or correct a malformed one |
|
|
66
|
+
| n | new entry after the current line (or in its book's section if the book is another one) |
|
|
67
|
+
| a | go to the quick-add bar |
|
|
68
|
+
| c | duplicate |
|
|
69
|
+
| d / Delete | delete |
|
|
70
|
+
| Space | comment out / restore (`%`) |
|
|
71
|
+
| b | insert a blank line after this group |
|
|
72
|
+
| p | insert a page break after this group |
|
|
73
|
+
| x | add a cross-reference (`alias \goto term`) |
|
|
74
|
+
| Alt+↑ / Alt+↓ | move the line up/down |
|
|
75
|
+
| / | filter (text, `book:2`, `page:45`), in all the sections |
|
|
76
|
+
| s | show the section in the Sections tab (for the parts of a book in the Topics, the section of this book) |
|
|
77
|
+
|
|
78
|
+
New entries always go to the section of their book (or to the Topics/Categories), and changing the book of an entry
|
|
79
|
+
moves it to the section of its new book.
|
|
80
|
+
|
|
81
|
+
## Everywhere
|
|
82
|
+
|
|
83
|
+
| Key | Action |
|
|
84
|
+
|---|---|
|
|
85
|
+
| Ctrl+S | save (a `.bak` copy of the original file is kept) |
|
|
86
|
+
| F5 | save and compile the PDF (then open it) |
|
|
87
|
+
| F2 | course metadata (code, title, date, version) |
|
|
88
|
+
| F3 | new book (creates its section) |
|
|
89
|
+
| F4 | Sections tab: rename, set or change the book (renumbering its entries) or its title, add, delete, move |
|
|
90
|
+
| Ctrl+Z / Ctrl+Y | undo / redo |
|
|
91
|
+
| F1 | this help |
|
|
92
|
+
| Ctrl+Q | quit |
|
|
93
|
+
|
|
94
|
+
The *title* of a book is the bold first level of the group of the Topics section holding its parts, all in this book
|
|
95
|
+
(`2a@\textbf{Recon}!1@...`): it is edited with the book's section (Sections tab, `e`), and `t` there goes to it. The
|
|
96
|
+
entry editor locks this first level on the parts of a book.
|
|
97
|
+
|
|
98
|
+
Tabs: **Entries** (the quick-add bar and the lines of the file), **Sections** (sections and books), **Preview**
|
|
99
|
+
(the index as it will be typeset), **Problems** (checks).
|
|
100
|
+
|
|
101
|
+
## `.idx` syntax reminder
|
|
102
|
+
|
|
103
|
+
- `\indexentry{text}{page}`; `key@text` sets the sort key; `a!b` makes `b` a sub-level of `a`; `|cmd` formats the page.
|
|
104
|
+
- Sort keys made of digits and letters (`2a`) go to *Topics*, digits only (`200`) to *Categories*, the others to the letters.
|
|
105
|
+
- `\blankline|comment` is a blank line, `|newpage \comment` a page break, `\rate{n}` stars, `\linux`, `\win`, ... icons.
|
|
106
|
+
"""
|
course_index/compiler.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""Compilation of a course index to PDF with makeindex and pdflatex."""
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .course import CourseInfo, data_file_for
|
|
13
|
+
from .idx import Document, Raw
|
|
14
|
+
|
|
15
|
+
__all__ = ["BuildResult", "TEMPLATE", "compile_pdf", "init_project", "missing_tools", "open_file", "template_dir"]
|
|
16
|
+
|
|
17
|
+
TEMPLATE = Path(__file__).parent / "template"
|
|
18
|
+
TIMEOUT = 300
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class BuildResult:
|
|
23
|
+
"""Outcome of a compilation."""
|
|
24
|
+
ok: bool
|
|
25
|
+
pdf: Path | None = None
|
|
26
|
+
errors: list = field(default_factory=list)
|
|
27
|
+
warnings: list = field(default_factory=list)
|
|
28
|
+
log: str = ""
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def summary(self):
|
|
32
|
+
if self.ok:
|
|
33
|
+
w = f" ({len(self.warnings)} warning{'s'[:len(self.warnings) != 1]})" if self.warnings else ""
|
|
34
|
+
return f"PDF written to {self.pdf}{w}"
|
|
35
|
+
return self.errors[0] if self.errors else "compilation failed"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def missing_tools():
|
|
39
|
+
"""List of the required programs that are not installed."""
|
|
40
|
+
return [t for t in ("makeindex", "pdflatex") if shutil.which(t) is None]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def template_dir(idx_path):
|
|
44
|
+
"""Folder holding main.tex and lib/ for an index: its own folder if it is a template project, else the bundled
|
|
45
|
+
template."""
|
|
46
|
+
folder = Path(idx_path).resolve().parent
|
|
47
|
+
if (folder / "main.tex").is_file() and (folder / "lib" / "std.ist").is_file():
|
|
48
|
+
return folder
|
|
49
|
+
return TEMPLATE
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def init_project(folder, force=False):
|
|
53
|
+
"""Copy the template (main.tex, data.tex, lib/) into a folder, keeping existing files unless forced."""
|
|
54
|
+
folder = Path(folder)
|
|
55
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
copied = []
|
|
57
|
+
for src in sorted(TEMPLATE.rglob("*")):
|
|
58
|
+
if src.is_dir() or "__pycache__" in src.parts:
|
|
59
|
+
continue
|
|
60
|
+
dst = folder / src.relative_to(TEMPLATE)
|
|
61
|
+
if dst.exists() and not force:
|
|
62
|
+
continue
|
|
63
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
shutil.copy2(src, dst)
|
|
65
|
+
copied.append(dst)
|
|
66
|
+
return copied
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _comment_lines(doc):
|
|
70
|
+
"""File line numbers belonging to comment blocks (makeindex parses their examples of \\indexentry too)."""
|
|
71
|
+
lines, n = set(), 1
|
|
72
|
+
for it in doc.items:
|
|
73
|
+
count = it.text.count("\n") + 1 if isinstance(it, Raw) else 1
|
|
74
|
+
if isinstance(it, Raw) and (it.is_comment_block or it.text.lstrip().startswith("%")):
|
|
75
|
+
lines.update(range(n, n + count))
|
|
76
|
+
n += count
|
|
77
|
+
return lines
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _parse_ilg(ilg, ignored):
|
|
81
|
+
"""Extract the errors and warnings of a makeindex log, skipping those located in comment blocks."""
|
|
82
|
+
errors, warnings = [], []
|
|
83
|
+
for m in re.finditer(r"^(!! Input index error|## Warning) \((?:file|input) = [^,]*, line = (\d+)[^)]*\):\s*\n"
|
|
84
|
+
r"\s*-- (.*)$", ilg, re.M):
|
|
85
|
+
line = int(m.group(2))
|
|
86
|
+
if line in ignored:
|
|
87
|
+
continue
|
|
88
|
+
msg = f"line {line}: {m.group(3).strip()}"
|
|
89
|
+
(errors if m.group(1).startswith("!!") else warnings).append(msg)
|
|
90
|
+
return errors, warnings
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _parse_latex_log(log):
|
|
94
|
+
"""Extract the errors of a pdflatex log (lines starting with '!' and the line where they occurred)."""
|
|
95
|
+
errors, lines = [], log.splitlines()
|
|
96
|
+
for i, line in enumerate(lines):
|
|
97
|
+
if line.startswith("! "):
|
|
98
|
+
ctx = next((x.strip() for x in lines[i+1:i+8] if re.match(r"^l\.\d+", x)), "")
|
|
99
|
+
errors.append(line[2:].strip() + (f" ({ctx})" if ctx else ""))
|
|
100
|
+
return errors
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def compile_pdf(idx_path, output=None, document=None, course=None):
|
|
104
|
+
"""Compile an index to PDF.
|
|
105
|
+
|
|
106
|
+
:param idx_path: path to the .idx file
|
|
107
|
+
:param output: PDF path (default: the .idx path with the .pdf extension)
|
|
108
|
+
:param document: Document to compile instead of the content of the file (e.g. unsaved changes)
|
|
109
|
+
:param course: CourseInfo to use instead of the index's data file
|
|
110
|
+
:return: BuildResult
|
|
111
|
+
"""
|
|
112
|
+
idx_path = Path(idx_path)
|
|
113
|
+
output = Path(output) if output else idx_path.with_suffix(".pdf")
|
|
114
|
+
missing = missing_tools()
|
|
115
|
+
if missing:
|
|
116
|
+
return BuildResult(False, errors=[f"{', '.join(missing)} not found: install a TeX distribution (e.g. "
|
|
117
|
+
f"TeX Live with texlive-latex-extra)"])
|
|
118
|
+
doc = document if document is not None else Document.load(idx_path)
|
|
119
|
+
if not any(e.kind == "ref" for _, e in doc.entries()):
|
|
120
|
+
# nothing to typeset (and makeindex 2.17 crashes on such an index)
|
|
121
|
+
return BuildResult(False, errors=["the index has no references yet: add some before compiling"])
|
|
122
|
+
if course is None:
|
|
123
|
+
data = data_file_for(idx_path)
|
|
124
|
+
course = CourseInfo.load(data) if data.exists() else CourseInfo.guess(idx_path)
|
|
125
|
+
tpl = template_dir(idx_path)
|
|
126
|
+
with tempfile.TemporaryDirectory(prefix="course-index-") as tmp:
|
|
127
|
+
tmp = Path(tmp)
|
|
128
|
+
shutil.copy2(tpl / "main.tex", tmp / "main.tex")
|
|
129
|
+
shutil.copytree(tpl / "lib", tmp / "lib")
|
|
130
|
+
original = (tpl / "data.tex").read_text(encoding="utf-8") if (tpl / "data.tex").exists() else None
|
|
131
|
+
(tmp / "data.tex").write_text(course.dumps(original), encoding="utf-8")
|
|
132
|
+
text = doc.dumps()
|
|
133
|
+
# makeindex 2.17 segfaults on a file ending with non-entry text without a final newline
|
|
134
|
+
(tmp / "main.idx").write_text(text if text.endswith("\n") else text + "\n", encoding="utf-8", newline="")
|
|
135
|
+
# files referenced with a relative path (images, \input, ...) are searched in the build folder, then in the
|
|
136
|
+
# folder of the index and in the template's folder (the trailing separator keeps TeX's default path)
|
|
137
|
+
folders = list(dict.fromkeys([str(idx_path.resolve().parent), str(tpl)]))
|
|
138
|
+
env = {**os.environ, 'TEXINPUTS': os.pathsep.join([".", *folders, os.environ.get("TEXINPUTS", "")])}
|
|
139
|
+
trace = [f"# build folder: {tmp}", f"# TEXINPUTS={env['TEXINPUTS']}"]
|
|
140
|
+
try:
|
|
141
|
+
cmd = ["makeindex", "-s", "lib/std.ist", "main.idx"]
|
|
142
|
+
trace.append(f"$ {' '.join(cmd)}")
|
|
143
|
+
mi = subprocess.run(cmd, cwd=tmp, capture_output=True, text=True, timeout=TIMEOUT, errors="replace",
|
|
144
|
+
env=env)
|
|
145
|
+
ilg = (tmp / "main.ilg").read_text(errors="replace") if (tmp / "main.ilg").exists() else mi.stderr
|
|
146
|
+
errors, warnings = _parse_ilg(ilg, _comment_lines(doc))
|
|
147
|
+
if mi.returncode != 0 or not (tmp / "main.ind").exists():
|
|
148
|
+
msg = f"makeindex crashed (exit code {mi.returncode})" if mi.returncode < 0 or mi.returncode > 128 \
|
|
149
|
+
else "makeindex failed"
|
|
150
|
+
return BuildResult(False, errors=errors or [msg], warnings=warnings,
|
|
151
|
+
log="\n".join(trace + [ilg.rstrip()]))
|
|
152
|
+
trace.append(ilg.rstrip())
|
|
153
|
+
# like Texmaker's quick build: do not halt on errors, a PDF is produced whenever possible
|
|
154
|
+
cmd = ["pdflatex", "-interaction=nonstopmode", "main.tex"]
|
|
155
|
+
trace += ["", f"$ {' '.join(cmd)}"]
|
|
156
|
+
tex = subprocess.run(cmd, cwd=tmp, capture_output=True, text=True, timeout=TIMEOUT, errors="replace",
|
|
157
|
+
env=env)
|
|
158
|
+
except subprocess.TimeoutExpired as e:
|
|
159
|
+
return BuildResult(False, errors=[f"{e.cmd[0]} timed out after {TIMEOUT} seconds"], log="\n".join(trace))
|
|
160
|
+
log = (tmp / "main.log").read_text(errors="replace") if (tmp / "main.log").exists() else tex.stdout
|
|
161
|
+
log = "\n".join(trace + [log])
|
|
162
|
+
pdf = tmp / "main.pdf"
|
|
163
|
+
latex_errors = _parse_latex_log(log)
|
|
164
|
+
if not pdf.exists():
|
|
165
|
+
return BuildResult(False, errors=latex_errors or ["pdflatex failed"], warnings=warnings, log=log)
|
|
166
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
shutil.copyfile(pdf, output)
|
|
168
|
+
return BuildResult(True, output, warnings=warnings + [f"LaTeX: {e}" for e in latex_errors], log=log)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def open_file(path): # pragma: no cover
|
|
172
|
+
"""Open a file with the default application of the system (e.g. the PDF viewer)."""
|
|
173
|
+
path = str(path)
|
|
174
|
+
if sys.platform.startswith("win"):
|
|
175
|
+
os.startfile(path)
|
|
176
|
+
return
|
|
177
|
+
cmd = ["open", path] if sys.platform == "darwin" else ["xdg-open", path]
|
|
178
|
+
subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
|
course_index/course.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""Course metadata, stored in the template's `data.tex`."""
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass, fields
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .idx import _group
|
|
8
|
+
|
|
9
|
+
__all__ = ["CourseInfo", "data_file_for"]
|
|
10
|
+
|
|
11
|
+
_FIELDS = {"code": "coursecode", "title": "coursetitle", "date": "coursedate", "version": "courseversion",
|
|
12
|
+
"author": "indexauthor"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class CourseInfo:
|
|
17
|
+
"""Course attributes used by the template (header, footer and book prefix of the page numbers)."""
|
|
18
|
+
code: str = "123"
|
|
19
|
+
title: str = "C\\coursecode\\ -- Course Title"
|
|
20
|
+
date: str = ""
|
|
21
|
+
version: str = ""
|
|
22
|
+
author: str = ""
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def display_title(self):
|
|
26
|
+
t = self.title.replace("\\coursecode", self.code).replace("\\ ", " ").replace("--", "–")
|
|
27
|
+
return re.sub(r"\s+", " ", t).strip()
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def parse(cls, text):
|
|
31
|
+
info, found = cls(), {}
|
|
32
|
+
for attr, macro in _FIELDS.items():
|
|
33
|
+
m = re.search(r"\\def\\" + macro + r"\s*(?=\{)", text)
|
|
34
|
+
if m:
|
|
35
|
+
j = _group(text, m.end())
|
|
36
|
+
if j > 0:
|
|
37
|
+
found[attr] = text[m.end() + 1:j - 1]
|
|
38
|
+
for attr, value in found.items():
|
|
39
|
+
setattr(info, attr, value)
|
|
40
|
+
if "author" not in found:
|
|
41
|
+
info.author = ""
|
|
42
|
+
return info
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def guess(cls, idx_path):
|
|
46
|
+
"""Default metadata for an index without data file, from its name (e.g. `sec504.idx` -> code 504)."""
|
|
47
|
+
stem = Path(idx_path).stem
|
|
48
|
+
m = re.search(r"\d+", stem)
|
|
49
|
+
info = cls()
|
|
50
|
+
if m and stem != "main":
|
|
51
|
+
info.code, info.title = m.group(0), stem.upper()
|
|
52
|
+
return info
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def load(cls, path):
|
|
56
|
+
return cls.parse(Path(path).read_text(encoding="utf-8"))
|
|
57
|
+
|
|
58
|
+
def dumps(self, original=None):
|
|
59
|
+
"""Serialize to `data.tex`, keeping the other lines of the original content if given."""
|
|
60
|
+
text = original or ""
|
|
61
|
+
for attr, macro in _FIELDS.items():
|
|
62
|
+
value = getattr(self, attr)
|
|
63
|
+
line = f"\\def\\{macro}{{{value}}}"
|
|
64
|
+
m = re.search(r"\\def\\" + macro + r"\s*(?=\{)", text)
|
|
65
|
+
if m and (j := _group(text, m.end())) > 0:
|
|
66
|
+
if attr == "author" and not value:
|
|
67
|
+
# \indexauthor must stay undefined when empty (main.tex tests \ifdefined)
|
|
68
|
+
end = j + (1 if text[j:j+1] == "\n" else 0)
|
|
69
|
+
text = text[:m.start()] + text[end:]
|
|
70
|
+
else:
|
|
71
|
+
text = text[:m.start()] + line + text[j:]
|
|
72
|
+
elif attr != "author" or value:
|
|
73
|
+
text = (text.rstrip("\n") + "\n" if text.strip() else "") + line + "\n"
|
|
74
|
+
return text
|
|
75
|
+
|
|
76
|
+
def save(self, path):
|
|
77
|
+
path = Path(path)
|
|
78
|
+
original = path.read_text(encoding="utf-8") if path.exists() else None
|
|
79
|
+
path.write_text(self.dumps(original), encoding="utf-8")
|
|
80
|
+
|
|
81
|
+
def as_dict(self):
|
|
82
|
+
return {f.name: getattr(self, f.name) for f in fields(self)}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def data_file_for(idx_path):
|
|
86
|
+
"""Course metadata file of an index: `<name>.data.tex` (several indexes in one folder) or `data.tex`."""
|
|
87
|
+
idx_path = Path(idx_path)
|
|
88
|
+
own, shared = idx_path.with_name(idx_path.stem + ".data.tex"), idx_path.with_name("data.tex")
|
|
89
|
+
if own.exists():
|
|
90
|
+
return own
|
|
91
|
+
if shared.exists() or idx_path.stem == "main":
|
|
92
|
+
return shared
|
|
93
|
+
return own
|