zman 0.1__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.
zman/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Python manual-page viewer for z/OS UNIX."""
2
+
3
+ __version__ = "0.1"
zman/renderer.py ADDED
@@ -0,0 +1,178 @@
1
+ """Rendering for plain-text pages and a conservative subset of roff."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import re
7
+ from pathlib import Path
8
+
9
+
10
+ class UnsupportedPage(ValueError):
11
+ """Raised when a page uses syntax this renderer cannot safely handle."""
12
+
13
+
14
+ _INLINE_ESCAPES = re.compile(
15
+ r"\\(?:f\[[^]]+\]|f.|[\\&\-~ 0e]|\(.{2}|\[[^]]+\])"
16
+ )
17
+ _UNKNOWN_ESCAPE = re.compile(r"\\(?:[A-Za-z]|\(.{2}|\[[^]]+\])")
18
+ _NAMED_CHARS = {
19
+ "em": "\u2014",
20
+ "en": "\u2013",
21
+ "bu": "*",
22
+ "co": "(C)",
23
+ "lq": '"',
24
+ "rq": '"',
25
+ }
26
+ _MACROS_WITH_TEXT = {"B", "I", "SM", "SB", "BR", "BI", "IR", "RB", "RI"}
27
+ _SUPPORTED_MACROS = _MACROS_WITH_TEXT | {
28
+ "TH", "SH", "SS", "P", "PP", "LP", "TP", "IP", "br", "sp",
29
+ "nf", "fi", "RS", "RE", "EX", "EE",
30
+ }
31
+
32
+
33
+ def _decode_page(data: bytes) -> str:
34
+ import locale
35
+
36
+ encodings = [locale.getpreferredencoding(False), "utf-8", "cp1047", "latin-1"]
37
+ for encoding in dict.fromkeys(encodings):
38
+ try:
39
+ return data.decode(encoding)
40
+ except (LookupError, UnicodeDecodeError):
41
+ continue
42
+ return data.decode("utf-8", errors="replace")
43
+
44
+
45
+ def read_page(path: Path) -> str:
46
+ """Read a possibly compressed manual page as text."""
47
+ data = path.read_bytes()
48
+ suffix = path.suffix.lower()
49
+ if suffix == ".gz":
50
+ try:
51
+ data = gzip.decompress(data)
52
+ except (OSError, EOFError) as exc:
53
+ raise UnsupportedPage(f"could not decompress {path}: {exc}") from exc
54
+ elif suffix == ".bz2":
55
+ try:
56
+ import bz2
57
+ except ImportError as exc:
58
+ raise UnsupportedPage("bzip2 support is unavailable") from exc
59
+ try:
60
+ data = bz2.decompress(data)
61
+ except (OSError, EOFError) as exc:
62
+ raise UnsupportedPage(f"could not decompress {path}: {exc}") from exc
63
+ elif suffix == ".xz":
64
+ try:
65
+ import lzma
66
+ except ImportError as exc:
67
+ raise UnsupportedPage("xz support is unavailable") from exc
68
+ try:
69
+ data = lzma.decompress(data)
70
+ except (OSError, EOFError, lzma.LZMAError) as exc:
71
+ raise UnsupportedPage(f"could not decompress {path}: {exc}") from exc
72
+ return _decode_page(data)
73
+
74
+
75
+ def _inline(text: str) -> str:
76
+ def replace(match: re.Match[str]) -> str:
77
+ escape = match.group(0)
78
+ if escape.startswith(r"\f"):
79
+ return ""
80
+ if escape == r"\&":
81
+ return ""
82
+ if escape == r"\-":
83
+ return "-"
84
+ if escape in (r"\ ", r"\~", r"\0"):
85
+ return " "
86
+ if escape == r"\e":
87
+ return "\\"
88
+ if escape == r"\\":
89
+ return "\\"
90
+ if escape.startswith(r"\("):
91
+ return _NAMED_CHARS.get(escape[2:], "")
92
+ if escape.startswith(r"\["):
93
+ name = escape[2:-1]
94
+ if name in _NAMED_CHARS:
95
+ return _NAMED_CHARS[name]
96
+ raise UnsupportedPage(f"unsupported roff character escape: {escape}")
97
+ return escape
98
+
99
+ result = _INLINE_ESCAPES.sub(replace, text)
100
+ unknown = _UNKNOWN_ESCAPE.search(result)
101
+ if unknown:
102
+ raise UnsupportedPage(f"unsupported roff escape: {unknown.group(0)}")
103
+ if r"\*" in result:
104
+ raise UnsupportedPage("roff string references are not supported")
105
+ return result
106
+
107
+
108
+ def _arguments(text: str) -> str:
109
+ return text.strip().strip('"')
110
+
111
+
112
+ def render_page(text: str) -> str:
113
+ """Render a plain-text page or common man macros to terminal-friendly text."""
114
+ text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\x85", "\n")
115
+ if not text.strip():
116
+ raise UnsupportedPage("the manual page is empty")
117
+
118
+ # Cat pages use backspace overstrikes for emphasis; keep the visible glyph.
119
+ if not any(line.startswith((".", "'")) for line in text.splitlines()):
120
+ plain = re.sub(r".\x08", "", text)
121
+ plain = plain.replace("\x08", "")
122
+ return plain.rstrip() + "\n"
123
+
124
+ output: list[str] = []
125
+ indent = 0
126
+ pending_tag = False
127
+ for line in text.splitlines():
128
+ if line.startswith((".", "'")):
129
+ command = line[1:].strip()
130
+ if not command:
131
+ output.append("")
132
+ continue
133
+ parts = command.split(None, 1)
134
+ macro = parts[0]
135
+ argument = parts[1] if len(parts) == 2 else ""
136
+ if macro not in _SUPPORTED_MACROS:
137
+ raise UnsupportedPage(f"unsupported roff macro: .{macro}")
138
+
139
+ if macro in {"TH", "nf", "fi", "EX", "EE"}:
140
+ continue
141
+ if macro in {"SH", "SS"}:
142
+ heading = _inline(_arguments(argument))
143
+ if output and output[-1]:
144
+ output.append("")
145
+ output.extend((heading.upper(), ""))
146
+ elif macro in {"P", "PP", "LP", "sp", "br"}:
147
+ if output and output[-1]:
148
+ output.append("")
149
+ elif macro == "TP":
150
+ pending_tag = True
151
+ elif macro == "IP":
152
+ label = _inline(_arguments(argument))
153
+ if label:
154
+ output.append(f"{' ' * (indent * 4)}{label}")
155
+ pending_tag = True
156
+ elif macro == "RS":
157
+ indent += 1
158
+ elif macro == "RE":
159
+ indent = max(0, indent - 1)
160
+ elif macro in _MACROS_WITH_TEXT:
161
+ value = _inline(_arguments(argument))
162
+ if value:
163
+ output.append(f"{' ' * (indent * 4)}{value}")
164
+ continue
165
+
166
+ value = _inline(line)
167
+ if pending_tag:
168
+ output.append(f"{' ' * (indent * 4)}{value}")
169
+ pending_tag = False
170
+ elif value:
171
+ output.append(f"{' ' * (indent * 4)}{value}")
172
+ elif output and output[-1]:
173
+ output.append("")
174
+
175
+ rendered = "\n".join(output).rstrip()
176
+ if not rendered:
177
+ raise UnsupportedPage("the manual page contains no printable text")
178
+ return rendered + "\n"
zman/selection.py ADDED
@@ -0,0 +1,321 @@
1
+ """A keyboard-driven, color-capable manual-page selector."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from typing import Optional, Sequence
8
+
9
+
10
+ _APROPOS_LINE = re.compile(
11
+ r"^\s*(?P<names>.+?)\s*\((?P<section>[^()]+)\)\s+-\s*(?P<description>.*)$"
12
+ )
13
+
14
+
15
+ class SelectionError(RuntimeError):
16
+ """Raised when an interactive page selection cannot be displayed."""
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ManPage:
21
+ name: str
22
+ section: str
23
+ description: str
24
+
25
+ @property
26
+ def label(self) -> str:
27
+ return f"{self.name}({self.section}) - {self.description}"
28
+
29
+
30
+ def parse_apropos_output(output: str) -> list[ManPage]:
31
+ """Parse standard `man -k` output into selectable manual pages."""
32
+ pages: list[ManPage] = []
33
+ seen: set[tuple[str, str]] = set()
34
+ for line in output.splitlines():
35
+ match = _APROPOS_LINE.match(line)
36
+ if match is None:
37
+ continue
38
+ name = match.group("names").split(",", 1)[0].strip()
39
+ section = match.group("section").strip()
40
+ key = (name, section)
41
+ if name and section and key not in seen:
42
+ pages.append(
43
+ ManPage(name, section, match.group("description").strip())
44
+ )
45
+ seen.add(key)
46
+ return pages
47
+
48
+
49
+ def filter_pages(
50
+ pages: Sequence[ManPage], query: str, whole_word: bool = False
51
+ ) -> list[ManPage]:
52
+ if not query:
53
+ return list(pages)
54
+ if whole_word:
55
+ pattern = re.compile(rf"(?<!\w){re.escape(query)}(?!\w)", re.IGNORECASE)
56
+ return [
57
+ page
58
+ for page in pages
59
+ if pattern.search(page.name) or pattern.search(page.description)
60
+ ]
61
+ folded_query = query.casefold()
62
+ return [page for page in pages if folded_query in page.label.casefold()]
63
+
64
+
65
+ def _color_attributes(curses) -> dict[str, int]:
66
+ attributes = {
67
+ "header": curses.A_BOLD,
68
+ "selected": curses.A_REVERSE | curses.A_BOLD,
69
+ "status": curses.A_BOLD,
70
+ "prompt": curses.A_UNDERLINE | curses.A_BOLD,
71
+ "tutorial": curses.A_BOLD,
72
+ }
73
+ try:
74
+ if not curses.has_colors():
75
+ return attributes
76
+ curses.start_color()
77
+ try:
78
+ curses.use_default_colors()
79
+ background = -1
80
+ except curses.error:
81
+ background = curses.COLOR_BLACK
82
+ colors = (
83
+ (1, curses.COLOR_BLACK, curses.COLOR_CYAN),
84
+ (2, curses.COLOR_YELLOW, background),
85
+ (3, curses.COLOR_BLACK, curses.COLOR_WHITE),
86
+ (4, curses.COLOR_GREEN, background),
87
+ (5, curses.COLOR_MAGENTA, background),
88
+ )
89
+ for pair, foreground, background in colors:
90
+ curses.init_pair(pair, foreground, background)
91
+ return {
92
+ "header": curses.color_pair(3) | curses.A_BOLD,
93
+ "selected": curses.color_pair(1) | curses.A_BOLD,
94
+ "status": curses.color_pair(2),
95
+ "prompt": curses.color_pair(4) | curses.A_BOLD,
96
+ "tutorial": curses.color_pair(5) | curses.A_BOLD,
97
+ }
98
+ except curses.error:
99
+ return attributes
100
+
101
+
102
+ def _write(screen, y: int, text: str, width: int, attribute: int = 0) -> None:
103
+ if width > 1:
104
+ screen.addnstr(y, 0, text, width - 1, attribute)
105
+
106
+
107
+ def _draw(
108
+ screen,
109
+ pages: Sequence[ManPage],
110
+ keyword: str,
111
+ filter_text: str,
112
+ find_text: str,
113
+ selected: int,
114
+ scroll: int,
115
+ status: str,
116
+ attributes: dict[str, int],
117
+ ) -> tuple[list[ManPage], int]:
118
+ height, width = screen.getmaxyx()
119
+ screen.erase()
120
+ if height < 5 or width < 2:
121
+ _write(screen, 0, "Resize terminal to view manual pages", width)
122
+ screen.refresh()
123
+ return [], 0
124
+
125
+ visible = filter_pages(pages, filter_text)
126
+ selected = max(0, min(selected, len(visible) - 1)) if visible else 0
127
+ list_top = 2
128
+ list_height = max(1, height - 4)
129
+ if selected < scroll:
130
+ scroll = selected
131
+ elif selected >= scroll + list_height:
132
+ scroll = selected - list_height + 1
133
+
134
+ header = f" ZMAN PAGES | Key: {keyword} | {len(visible)}/{len(pages)} "
135
+ _write(screen, 0, header.ljust(width - 1), width, attributes["header"])
136
+ prompt = f"Filter: {filter_text or '(none)'} Find: {find_text or '(none)'}"
137
+ _write(screen, 1, prompt, width, attributes["prompt"])
138
+
139
+ if not visible:
140
+ _write(screen, list_top, "No pages match the current filter.", width)
141
+ else:
142
+ for row, page in enumerate(visible[scroll : scroll + list_height]):
143
+ index = scroll + row
144
+ prefix = "> " if index == selected else " "
145
+ attribute = attributes["selected"] if index == selected else 0
146
+ _write(
147
+ screen,
148
+ list_top + row,
149
+ prefix + page.label,
150
+ width,
151
+ attribute,
152
+ )
153
+
154
+ if height > 2:
155
+ _write(screen, height - 2, status, width, attributes["status"])
156
+ if height > 3:
157
+ footer = " Type: filter /: find Ctrl+N/P: next/previous Enter: open F1: tutorial q: quit "
158
+ _write(screen, height - 1, footer, width, attributes["header"])
159
+ screen.refresh()
160
+ return visible, scroll
161
+
162
+
163
+ def _prompt_find(screen, curses, width: int) -> str:
164
+ text: list[str] = []
165
+ while True:
166
+ prompt = "Find: " + "".join(text)
167
+ row = screen.getmaxyx()[0] - 2
168
+ _write(screen, row, " " * max(0, width - 1), width)
169
+ _write(screen, row, prompt, width)
170
+ screen.refresh()
171
+ key = screen.get_wch()
172
+ if key in ("\n", "\r", getattr(curses, "KEY_ENTER", -1)):
173
+ return "".join(text)
174
+ if key == "\x1b":
175
+ return ""
176
+ if key in (getattr(curses, "KEY_BACKSPACE", -1), "\x7f", "\b"):
177
+ if text:
178
+ text.pop()
179
+ elif key == "\x15":
180
+ text.clear()
181
+ elif isinstance(key, str) and key.isprintable():
182
+ text.append(key)
183
+
184
+
185
+ def _find_match(
186
+ pages: Sequence[ManPage], term: str, start: int, direction: int
187
+ ) -> Optional[int]:
188
+ if not pages or not term:
189
+ return None
190
+ folded_term = term.casefold()
191
+ for offset in range(1, len(pages) + 1):
192
+ index = (start + direction * offset) % len(pages)
193
+ if folded_term in pages[index].label.casefold():
194
+ return index
195
+ return None
196
+
197
+
198
+ def _show_tutorial(screen, curses, attributes: dict[str, int]) -> None:
199
+ lines = [
200
+ "Manual page selection",
201
+ "",
202
+ "Type characters to filter the list; Backspace edits the filter.",
203
+ "Ctrl+U clears the filter.",
204
+ "/ prompts for a find term in the filtered list.",
205
+ "Ctrl+N / Ctrl+P finds the next / previous match.",
206
+ "Up/Down or Page Up/Page Down moves the selection.",
207
+ "Enter opens the selected page.",
208
+ "F1 shows this tutorial; q or Esc exits.",
209
+ "",
210
+ "Press any key to return.",
211
+ ]
212
+ height, width = screen.getmaxyx()
213
+ box_height = min(height - 2, len(lines) + 2)
214
+ box_width = min(width - 2, max(len(line) for line in lines) + 4)
215
+ if box_height < 3 or box_width < 12:
216
+ _write(screen, max(0, height - 2), "Terminal too small for tutorial", width)
217
+ screen.refresh()
218
+ screen.get_wch()
219
+ return
220
+
221
+ top = (height - box_height) // 2
222
+ left = (width - box_width) // 2
223
+ window = curses.newwin(box_height, box_width, top, left)
224
+ window.attron(attributes["tutorial"])
225
+ window.box()
226
+ window.attroff(attributes["tutorial"])
227
+ for row, line in enumerate(lines[: box_height - 2], start=1):
228
+ attribute = attributes["tutorial"] if row == 1 else 0
229
+ window.addnstr(row, 2, line, box_width - 4, attribute)
230
+ window.refresh()
231
+ window.get_wch()
232
+
233
+
234
+ def _selection_screen(screen, pages, keyword, curses):
235
+ screen.keypad(True)
236
+ attributes = _color_attributes(curses)
237
+ filter_text = ""
238
+ find_text = ""
239
+ selected = 0
240
+ scroll = 0
241
+ status = "Type to filter; press / to find; F1 opens the tutorial."
242
+
243
+ while True:
244
+ visible, scroll = _draw(
245
+ screen,
246
+ pages,
247
+ keyword,
248
+ filter_text,
249
+ find_text,
250
+ selected,
251
+ scroll,
252
+ status,
253
+ attributes,
254
+ )
255
+ selected = max(0, min(selected, len(visible) - 1)) if visible else 0
256
+ key = screen.get_wch()
257
+
258
+ if key == getattr(curses, "KEY_F1", -1):
259
+ _show_tutorial(screen, curses, attributes)
260
+ elif key in ("\x1b", "\x03"):
261
+ if filter_text:
262
+ filter_text = ""
263
+ selected = 0
264
+ scroll = 0
265
+ else:
266
+ return None
267
+ elif key == "q" and not filter_text:
268
+ return None
269
+ elif key in ("\n", "\r", getattr(curses, "KEY_ENTER", -1)):
270
+ return visible[selected] if visible else None
271
+ elif key == getattr(curses, "KEY_UP", -1):
272
+ selected = max(0, selected - 1)
273
+ elif key == getattr(curses, "KEY_DOWN", -1):
274
+ selected = min(len(visible) - 1, selected + 1) if visible else 0
275
+ elif key == getattr(curses, "KEY_PPAGE", -1):
276
+ selected = max(0, selected - max(1, screen.getmaxyx()[0] - 4))
277
+ elif key == getattr(curses, "KEY_NPAGE", -1):
278
+ selected = min(
279
+ len(visible) - 1,
280
+ selected + max(1, screen.getmaxyx()[0] - 4),
281
+ ) if visible else 0
282
+ elif key in (getattr(curses, "KEY_BACKSPACE", -1), "\x7f", "\b"):
283
+ filter_text = filter_text[:-1]
284
+ selected = 0
285
+ scroll = 0
286
+ elif key == "\x15":
287
+ filter_text = ""
288
+ selected = 0
289
+ scroll = 0
290
+ elif key == "/":
291
+ find_text = _prompt_find(screen, curses, screen.getmaxyx()[1])
292
+ match = _find_match(visible, find_text, selected - 1, 1)
293
+ if match is None and find_text:
294
+ status = f"No match for: {find_text}"
295
+ elif match is not None:
296
+ selected = match
297
+ status = f"Find: {find_text}"
298
+ elif key in ("\x0e", "\x10") and find_text:
299
+ direction = 1 if key == "\x0e" else -1
300
+ match = _find_match(visible, find_text, selected, direction)
301
+ if match is not None:
302
+ selected = match
303
+ status = f"Find: {find_text}"
304
+ else:
305
+ status = f"No match for: {find_text}"
306
+ elif isinstance(key, str) and key.isprintable():
307
+ filter_text += key
308
+ selected = 0
309
+ scroll = 0
310
+ status = "Type to filter; press / to find; F1 opens the tutorial."
311
+
312
+
313
+ def select_page(pages: Sequence[ManPage], keyword: str) -> Optional[ManPage]:
314
+ try:
315
+ import curses
316
+ except ImportError as exc:
317
+ raise SelectionError("interactive selection requires Python curses support") from exc
318
+ try:
319
+ return curses.wrapper(_selection_screen, list(pages), keyword, curses)
320
+ except curses.error as exc:
321
+ raise SelectionError(f"unable to start the selection screen: {exc}") from exc
zman/zmanp.py ADDED
@@ -0,0 +1,328 @@
1
+ #!/usr/bin/env python3
2
+ """Command-line entry point for zman and its man-compatible alias."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Mapping, Optional
13
+
14
+ if __package__ in (None, ""):
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
16
+
17
+ from zman import __version__
18
+ from zman.renderer import UnsupportedPage, read_page, render_page
19
+ from zman.selection import (
20
+ ManPage,
21
+ SelectionError,
22
+ filter_pages,
23
+ parse_apropos_output,
24
+ select_page,
25
+ )
26
+
27
+ _COMPRESSION_SUFFIXES = (".gz", ".bz2", ".xz")
28
+ _DEFAULT_MANPATH = (
29
+ "/usr/share/man",
30
+ "/usr/local/share/man",
31
+ "/usr/man",
32
+ "/usr/local/man",
33
+ )
34
+ _SECTION_PATTERN = re.compile(r"^[0-9][A-Za-z0-9]*$")
35
+
36
+
37
+ def _man_directories(env: dict[str, str]) -> list[Path]:
38
+ configured = env.get("MANPATH")
39
+ roots = configured.split(os.pathsep) if configured else list(_DEFAULT_MANPATH)
40
+ directories: list[Path] = []
41
+ for root in roots:
42
+ if not root:
43
+ continue
44
+ path = Path(root)
45
+ if path.name.startswith("man") and path.is_dir():
46
+ directories.append(path)
47
+ continue
48
+ try:
49
+ children = sorted(
50
+ child for child in path.iterdir()
51
+ if child.is_dir() and child.name.startswith("man")
52
+ )
53
+ except OSError:
54
+ continue
55
+ directories.extend(children)
56
+ return directories
57
+
58
+
59
+ def _name_description(rendered: str) -> str:
60
+ in_name_section = False
61
+ for line in rendered.splitlines():
62
+ value = line.strip()
63
+ if not in_name_section:
64
+ in_name_section = value.upper() == "NAME"
65
+ continue
66
+ if not value:
67
+ continue
68
+ if value.isupper():
69
+ return ""
70
+ match = re.match(r"^.+?\s+-\s+(.+)$", value)
71
+ if match:
72
+ return match.group(1).strip()
73
+ return ""
74
+
75
+
76
+ def _local_apropos_pages(keyword: str) -> list[ManPage]:
77
+ pages: list[ManPage] = []
78
+ seen: set[tuple[str, str]] = set()
79
+ scan_error: Optional[Exception] = None
80
+ for directory in _man_directories(os.environ):
81
+ try:
82
+ entries = sorted(directory.iterdir())
83
+ except OSError:
84
+ continue
85
+ for entry in entries:
86
+ if not entry.is_file():
87
+ continue
88
+ filename = entry.name
89
+ for compression in _COMPRESSION_SUFFIXES:
90
+ if filename.endswith(compression):
91
+ filename = filename[: -len(compression)]
92
+ break
93
+ match = re.fullmatch(r"(.+)\.([0-9][A-Za-z0-9]*)", filename)
94
+ if match is None:
95
+ continue
96
+ name, section = match.groups()
97
+ key = (name, section)
98
+ if key in seen:
99
+ continue
100
+ try:
101
+ description = _name_description(render_page(read_page(entry)))
102
+ except (OSError, UnsupportedPage) as exc:
103
+ scan_error = scan_error or exc
104
+ continue
105
+ if description:
106
+ pages.append(ManPage(name, section, description))
107
+ seen.add(key)
108
+
109
+ if scan_error is not None:
110
+ print(
111
+ f"zman: unable to read a local manual page: {scan_error}",
112
+ file=sys.stderr,
113
+ )
114
+ if keyword == ".":
115
+ return pages
116
+ return filter_pages(pages, keyword)
117
+
118
+
119
+ def find_page(name: str, section: Optional[str], env: Mapping[str, str]) -> Optional[Path]:
120
+ """Find a page using MANPATH and standard man-directory layouts."""
121
+ direct_path = Path(name)
122
+ if direct_path.is_file():
123
+ return direct_path
124
+
125
+ if section is None:
126
+ match = re.fullmatch(r"(.+)\(([0-9][A-Za-z0-9]*)\)", name)
127
+ if match:
128
+ name, section = match.groups()
129
+
130
+ candidates: list[Path] = []
131
+ for directory in _man_directories(env):
132
+ try:
133
+ for entry in directory.iterdir():
134
+ if not entry.is_file():
135
+ continue
136
+ filename = entry.name
137
+ for compression in ("", *_COMPRESSION_SUFFIXES):
138
+ suffix = filename.removesuffix(compression) if compression else filename
139
+ match = re.fullmatch(r"(.+)\.([0-9][A-Za-z0-9]*)", suffix)
140
+ if not match:
141
+ continue
142
+ page_name, page_section = match.groups()
143
+ if page_name == name and (section is None or section == page_section):
144
+ candidates.append(entry)
145
+ break
146
+ except OSError:
147
+ continue
148
+ return sorted(candidates, key=lambda path: (path.suffix, str(path)))[0] if candidates else None
149
+
150
+
151
+ def _requested_page(arguments: list[str]) -> Optional[tuple[str, Optional[str]]]:
152
+ if len(arguments) == 1 and not arguments[0].startswith("-"):
153
+ return arguments[0], None
154
+ if (
155
+ len(arguments) == 2
156
+ and _SECTION_PATTERN.fullmatch(arguments[0])
157
+ and not arguments[1].startswith("-")
158
+ ):
159
+ return arguments[1], arguments[0]
160
+ return None
161
+
162
+
163
+ def _fallback(arguments: list[str], reason: Optional[str] = None) -> int:
164
+ if reason is not None:
165
+ print(f"zman: {reason}; falling back to zotman", file=sys.stderr)
166
+ zotman = shutil.which("zotman")
167
+ if zotman is None:
168
+ print("zman: zotman was not found on PATH", file=sys.stderr)
169
+ return 127
170
+ try:
171
+ return subprocess.run([zotman, *arguments], check=False).returncode
172
+ except OSError as exc:
173
+ print(f"zman: unable to run zotman: {exc}", file=sys.stderr)
174
+ return 127
175
+
176
+
177
+ def _usage() -> str:
178
+ return (
179
+ "Usage: man [section] page\n"
180
+ " zman -m page\n"
181
+ " zman -k keyword\n"
182
+ " zman -kw word\n"
183
+ " zman [section] page\n"
184
+ " zman path-to-page\n"
185
+ " zman\n"
186
+ "With no page, zman lists the results of man -k .\n"
187
+ "Unsupported requests and pages are passed to zotman.\n"
188
+ )
189
+
190
+
191
+ def _is_zman_launcher(path: Path) -> bool:
192
+ try:
193
+ return b"zman.zmanp" in path.read_bytes()[:4096]
194
+ except OSError:
195
+ return False
196
+
197
+
198
+ def _find_external_man() -> Optional[str]:
199
+ for path_entry in os.environ.get("PATH", "").split(os.pathsep):
200
+ candidate = Path(path_entry or ".") / "man"
201
+ if not candidate.is_file() or _is_zman_launcher(candidate):
202
+ continue
203
+ if os.name != "nt" and not os.access(candidate, os.X_OK):
204
+ continue
205
+ return str(candidate)
206
+ return None
207
+
208
+
209
+ def _apropos_commands(keyword: str) -> list[list[str]]:
210
+ commands: list[list[str]] = []
211
+ man = _find_external_man()
212
+ if man is not None:
213
+ commands.append([man, "-k", keyword])
214
+ zotman = shutil.which("zotman")
215
+ if zotman is not None:
216
+ commands.append([zotman, "-k", keyword])
217
+ return commands
218
+
219
+
220
+ def _load_apropos_pages(keyword: str) -> Optional[list[ManPage]]:
221
+ commands = _apropos_commands(keyword)
222
+ last_error = ""
223
+ for command in commands:
224
+ try:
225
+ result = subprocess.run(
226
+ command,
227
+ check=False,
228
+ capture_output=True,
229
+ text=True,
230
+ )
231
+ except OSError as exc:
232
+ last_error = f"unable to run {command[0]}: {exc}"
233
+ continue
234
+ if result.returncode != 0:
235
+ last_error = result.stderr.strip() or (
236
+ f"{command[0]} -k exited with status {result.returncode}"
237
+ )
238
+ continue
239
+ pages = parse_apropos_output(result.stdout)
240
+ if pages:
241
+ return pages
242
+ if result.stdout.strip():
243
+ last_error = f"{command[0]} -k returned no parseable manual pages"
244
+
245
+ local_pages = _local_apropos_pages(keyword)
246
+ if local_pages:
247
+ return local_pages
248
+ if not commands:
249
+ print(
250
+ "zman: neither a separate man command nor zotman is available for man -k",
251
+ file=sys.stderr,
252
+ )
253
+ return None
254
+ if last_error:
255
+ print(f"zman: unable to list manual pages: {last_error}", file=sys.stderr)
256
+ return None
257
+ return []
258
+
259
+
260
+ def _select_from_index(keyword: str, whole_word: bool = False) -> int:
261
+ pages = _load_apropos_pages(keyword)
262
+ if pages is None:
263
+ return 127
264
+ if whole_word:
265
+ pages = filter_pages(pages, keyword, whole_word=True)
266
+ if not pages:
267
+ print(f"zman: no manual pages match {keyword!r}", file=sys.stderr)
268
+ return 1
269
+ try:
270
+ selected = select_page(pages, keyword)
271
+ except SelectionError as exc:
272
+ print(f"zman: {exc}", file=sys.stderr)
273
+ return 1
274
+ if selected is None:
275
+ return 0
276
+ return _open_page([selected.section, selected.name])
277
+
278
+
279
+ def _open_page(arguments: list[str]) -> int:
280
+ request = _requested_page(arguments)
281
+ if request is None:
282
+ return _fallback(arguments, "request is not supported locally")
283
+
284
+ page_name, section = request
285
+ page_path = find_page(page_name, section, os.environ)
286
+ if page_path is None:
287
+ return _fallback(arguments)
288
+
289
+ try:
290
+ rendered = render_page(read_page(page_path))
291
+ except (OSError, UnsupportedPage) as exc:
292
+ return _fallback(arguments, f"cannot process {page_path}: {exc}")
293
+
294
+ sys.stdout.write(rendered)
295
+ return 0
296
+
297
+
298
+ def main(argv: Optional[list[str]] = None) -> int:
299
+ arguments = list(sys.argv[1:] if argv is None else argv)
300
+ if arguments in (["-h"], ["--help"]):
301
+ print(_usage(), end="")
302
+ return 0
303
+ if arguments in (["-V"], ["--version"]):
304
+ print(f"zman {__version__}")
305
+ return 0
306
+
307
+ if not arguments:
308
+ return _select_from_index(".")
309
+ if arguments[0] in ("-m", "--manpage"):
310
+ if len(arguments) != 2:
311
+ print("zman: -m requires one manual page name", file=sys.stderr)
312
+ return 2
313
+ return _open_page([arguments[1]])
314
+ if arguments[0] == "-kw":
315
+ if len(arguments) < 2:
316
+ print("zman: -kw requires a word", file=sys.stderr)
317
+ return 2
318
+ return _select_from_index(" ".join(arguments[1:]), whole_word=True)
319
+ if arguments[0] in ("-k", "--keyword"):
320
+ if len(arguments) < 2:
321
+ print("zman: -k requires a keyword", file=sys.stderr)
322
+ return 2
323
+ return _select_from_index(" ".join(arguments[1:]))
324
+ return _open_page(arguments)
325
+
326
+
327
+ if __name__ == "__main__":
328
+ raise SystemExit(main())
@@ -0,0 +1,98 @@
1
+ .TH ZMAN 1 "November 2026" "zman 0.1" "User Commands"
2
+ .SH NAME
3
+ zman, man \- view manual pages with a zotman fallback
4
+ .SH SYNOPSIS
5
+ .B man
6
+ [\fIsection\fR] \fIpage\fR
7
+ .br
8
+ .B zman
9
+ [\fB\-m\fR \fIpage\fR | \fB\-k\fR \fIkeyword\fR | \fB\-kw\fR \fIword\fR]
10
+ .br
11
+ .B zman
12
+ [\fIsection\fR] \fIpage\fR
13
+ .br
14
+ .B zman
15
+ \fIpath-to-page\fR
16
+ .br
17
+ .B zman
18
+ .SH DESCRIPTION
19
+ .B zman
20
+ is a lightweight manual-page viewer for z/OS UNIX. It renders plain text and
21
+ a subset of common roff man-page macros.
22
+ .PP
23
+ With no page argument, zman obtains the page list by running
24
+ .B "man -k ."
25
+ It displays the results in a selectable list that can be filtered and searched
26
+ interactively. The
27
+ .B man
28
+ command is an alias for
29
+ .BR zman .
30
+ If a request or page cannot be rendered, zman invokes
31
+ .B zotman
32
+ with the original arguments.
33
+ .SH OPTIONS
34
+ .TP
35
+ .B \-m, \-\-manpage page
36
+ Display the named manual page.
37
+ .TP
38
+ .B \-k, \-\-keyword keyword
39
+ Display a selectable list of pages matching the keyword.
40
+ .TP
41
+ .B \-kw word
42
+ Display a selectable list of pages where the word occurs as a whole word in
43
+ the page name or description.
44
+ .TP
45
+ .B \-h, \-\-help
46
+ Display command usage and exit.
47
+ .TP
48
+ .B \-V, \-\-version
49
+ Display the version and exit.
50
+ .SH SELECTION LIST
51
+ Type characters to filter the list. Use Backspace to remove a character and
52
+ Ctrl+U to clear the filter. Press
53
+ .B /
54
+ to enter a find term in the filtered list; Ctrl+N and Ctrl+P move to the next
55
+ and previous match.
56
+ .PP
57
+ Use Up/Down or Page Up/Page Down to move through the list. Press Enter to open
58
+ the selected page, q or Esc to exit, or F1 to display the interactive tutorial.
59
+ The interface uses colors when supported by the terminal.
60
+ .SH PAGE LOOKUP
61
+ Page lookup uses
62
+ .B MANPATH
63
+ when set. Otherwise, zman checks
64
+ .IR /usr/share/man ,
65
+ .IR /usr/local/share/man ,
66
+ .IR /usr/man ,
67
+ and
68
+ .IR /usr/local/man .
69
+ Plain, gzip, bzip2, and xz-compressed pages are supported when the Python
70
+ standard-library codec is available.
71
+ .SH FALLBACK
72
+ Unsupported requests, missing pages, unsupported roff syntax, and page
73
+ read/decompression errors are passed to
74
+ .BR zotman .
75
+ For page listing, zman tries a separate
76
+ .B man
77
+ command with
78
+ .BR \-k ;
79
+ if unavailable or unusable, it tries
80
+ .BR zotman \-k .
81
+ The exit status is the status returned by zotman. If zotman is not on
82
+ .BR PATH ,
83
+ zman reports the error and exits with status 127.
84
+ .SH INSTALLATION
85
+ Install with the project's
86
+ .B install.py
87
+ script. On z/OS USS, install the zopen
88
+ .B man-db
89
+ package and run
90
+ .B mandb
91
+ to index the installed manual page. Tag installed scripts and Python sources
92
+ as ISO8859-1; see the project README for the commands.
93
+ .SH REQUIREMENTS
94
+ Python 3.9 or newer. The selection list requires a Python build with the
95
+ .B curses
96
+ module. The viewer otherwise uses the Python standard library.
97
+ .SH LICENSE
98
+ Distributed under the MIT License.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: zman
3
+ Version: 0.1
4
+ Summary: A Python man-page viewer for z/OS UNIX with zotman fallback
5
+ Author: zman contributors
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # zman
13
+
14
+ A small, dependency-free Python manual-page viewer for z/OS UNIX. It is an
15
+ independent CLI implementation inspired by [Qman](https://github.com/plp13/qman),
16
+ not a port of its C source or its interactive terminal UI.
17
+
18
+ The `zman` and `man` commands render plain-text pages and a useful subset of
19
+ roff man-page macros. If a request cannot be handled locally, zman runs
20
+ `zotman` with the original arguments. This lets z/OS Open Tools handle pages
21
+ that need its formatter or database.
22
+
23
+ ## Install without pip
24
+
25
+ Requires Python 3.9 or newer. The installer uses only the Python standard
26
+ library:
27
+
28
+ ```sh
29
+ python3 install.py
30
+ ```
31
+
32
+ The default prefix is `/usr/local`. To install to a user-writable prefix, run
33
+ `python3 install.py --prefix "$HOME/.local"` or set `PREFIX`. The installer
34
+ copies the Python modules, creates executable `zman` and `man` launchers, and
35
+ installs `zman.1`. If `chtag` is available, it tags installed files as
36
+ ISO8859-1. Ensure the prefix's `bin` directory is on `PATH` and `zotman` is on
37
+ `PATH` for fallback handling. For a non-default prefix, include its
38
+ `share/man` directory in `MANPATH` to find the installed page.
39
+
40
+ The `man` launcher may replace the usual `man` command when first on `PATH`;
41
+ it invokes `zotman` whenever it cannot render a request.
42
+
43
+ ## z/OS USS
44
+
45
+ The Git attributes keep source and documentation files in LF format and encode
46
+ the working tree as ISO8859-1. The installer uses `chtag` to tag installed
47
+ launchers, Python modules, and the man page when `chtag` is available. If the
48
+ installer reports that `chtag` is missing, tag the installed files manually:
49
+
50
+ ```sh
51
+ prefix=/usr/local
52
+ for file in "$prefix/bin/zman" "$prefix/bin/man" "$prefix/share/man/man1/zman.1"; do
53
+ chtag -tc ISO8859-1 "$file"
54
+ done
55
+ find "$prefix/lib/zman/zman" -type f -name '*.py' -exec chtag -tc ISO8859-1 {} \;
56
+ ```
57
+
58
+ Install the zopen `man-db` package and run `mandb` to index the installed
59
+ manual page. The page is installed under `share/man/man1`.
60
+
61
+ ## Use
62
+
63
+ ```sh
64
+ man
65
+ man -m printf
66
+ man -k printf
67
+ man -kw print
68
+ man printf
69
+ man 1 printf
70
+ zman ./my-command.1
71
+ ./src/zman/zmanp.py --version
72
+ ```
73
+
74
+ With no page, zman runs a separate `man -k .` command and opens an interactive
75
+ list of available pages; it skips its own `man` launcher and tries `zotman -k`
76
+ if the separate command is unavailable or returns unusable output. If neither
77
+ command returns parseable results, zman indexes local manual pages by their
78
+ `NAME` sections. Use `-k keyword` to list pages containing the keyword, or
79
+ `-kw word` to match a whole word in a page name or description. Use `-m page`
80
+ to display a page.
81
+ The list supports type-to-filter, `/` to find, Ctrl+N/Ctrl+P to move between
82
+ find matches, and F1 for an interactive tutorial. The interface uses terminal
83
+ colors when available and falls back to monochrome attributes otherwise.
84
+
85
+ Page lookup uses `MANPATH` when set, then checks the common locations
86
+ `/usr/share/man`, `/usr/local/share/man`, `/usr/man`, and `/usr/local/man`.
87
+ Plain, gzip, bzip2, and xz-compressed pages are supported when the corresponding
88
+ Python standard-library codec is available.
89
+
90
+ Requests that are not supported locally and pages with unsupported roff
91
+ constructs are passed through to `zotman`. If `zotman` is not installed, zman
92
+ prints an error and exits with status 127.
93
+
94
+ This initial viewer does not implement Qman's full page navigation, in-page
95
+ search, or hyperlinks.
96
+
97
+ The page-selection screen requires a Python build with the standard-library
98
+ `curses` module. Direct page display does not require curses.
99
+
100
+ ## Development
101
+
102
+ Run the test suite without installing the project:
103
+
104
+ ```sh
105
+ PYTHONPATH=src python3 -m unittest discover -s tests
106
+ ```
107
+
108
+ The project's `pyproject.toml` also supports package builds for environments
109
+ that use pip, but pip is not required to install or run the program.
@@ -0,0 +1,11 @@
1
+ zman/__init__.py,sha256=4G9GRyd1i7_2UkCY-h1JF8YjQ3lfO4-NzNKWg4tKFcs,68
2
+ zman/renderer.py,sha256=Zibl50RGQIL-Tc5tQbkFE3vU9cWqmAImRs4kxUXeg9U,6004
3
+ zman/selection.py,sha256=y8AONNBJFYQqAq_F4HkKCvZ7DCieG0hBL7mwB4gNkug,11054
4
+ zman/zmanp.py,sha256=OxsAfxz6Ji3_K6YfKWKWwXEPWh69G2mcvfhuAosdpko,10508
5
+ zman-0.1.data/data/share/man/man1/zman.1,sha256=Rhywo2FEDmVn97GcZaGfcSlVJIoTs9btOs6IUtPs4uo,2771
6
+ zman-0.1.dist-info/licenses/LICENSE,sha256=gCLCSrp4fl7lIV5Vz2jblbTy3FLVpwSEFoLjoXaNgqI,1074
7
+ zman-0.1.dist-info/METADATA,sha256=pdjMyF0DLUO3PTW-OB7HxmDBGDcDSGAlOxMGmKGiENU,4172
8
+ zman-0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ zman-0.1.dist-info/entry_points.txt,sha256=n2revQQ409Rt-_v5eq8GnRyJqQB1TF_FExbv1D514WY,63
10
+ zman-0.1.dist-info/top_level.txt,sha256=-GJ2kR0LBBqDm8VByePrySvoQ1-TGflHkYeHcJCrYbQ,5
11
+ zman-0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ man = zman.zmanp:main
3
+ zman = zman.zmanp:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zman 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
+ zman