1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::path::PathBuf;
use clap::Parser;
use clap::builder::styling::{AnsiColor, Color, Style};
use clap::builder::Styles;
const HELP_STYLES: Styles = Styles::styled()
.header(Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Yellow))))
.usage(Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Yellow))))
.literal(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))))
.placeholder(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))));
#[derive(Parser, Debug, Clone)]
#[command(name = "tess", version, about = "A less-style terminal pager.", styles = HELP_STYLES)]
pub struct Args {
/// Chop long lines instead of wrapping.
#[arg(short = 'S', long = "chop-long-lines")]
pub chop: bool,
/// Force the content type for `--prettify` (otherwise auto-detected from
/// the filename extension and the first bytes). Values:
/// `auto`, `raw`, `json`, `yaml`, `toml`, `xml`, `html`, `csv`.
/// Setting this implies `--prettify` (unless the value is `raw`/`auto`).
#[arg(long = "content-type", value_name = "TYPE")]
pub content_type: Option<String>,
/// With `--filter`, dim non-matching lines instead of hiding them. Keeps
/// surrounding context visible.
#[arg(long = "dim")]
pub dim: bool,
/// Render each parsed line through this template instead of showing the
/// raw line. Syntax: `<fieldname>` placeholders, `\<` for literal `<`,
/// `\\` for literal `\`. Example: `--display '[<time>] <status> <msg>'`.
/// Overrides the format's `display` key (if set). Requires `--format`.
/// Search still matches against the raw line.
#[arg(long = "display", value_name = "TEMPLATE")]
pub display: Option<String>,
/// Print a curated list of usage examples and exit.
#[arg(long = "examples")]
pub examples: bool,
/// Filter visible lines by parsed field. Repeatable; multiple filters AND.
/// Operators: `=` (exact), `!=` (exact ≠), `~` (regex), `!~` (regex ≠),
/// `<`, `<=`, `>`, `>=` (numeric if both sides parse as numbers, else
/// lexicographic). Examples: `--filter status=500`, `--filter ip~^10\.`,
/// `--filter 'status>=500'` (quote `<` and `>` to avoid shell redirection).
/// Requires `--format`.
#[arg(long = "filter", value_name = "FIELD<op>VALUE")]
pub filter: Vec<String>,
/// Follow mode: keep watching the source for new bytes (like `tail -f`).
/// Jumps to the bottom on startup. Toggle with Shift-F at runtime.
#[arg(short = 'f', long = "follow")]
pub follow: bool,
/// Apply a named log format (built-in or user-defined in
/// ~/.config/tess/formats.toml). Required by `--filter`.
#[arg(long = "format", value_name = "NAME")]
pub format: Option<String>,
/// Filter visible lines by regex against the raw line. Repeatable;
/// multiple `--grep` arguments AND. Works on any input — no `--format`
/// required. Composes with `--filter` (both must match) and with
/// `--dim` (non-matches stay visible but faded).
/// Example: `--grep error --grep '^\['`.
#[arg(long = "grep", value_name = "PATTERN")]
pub grep: Vec<String>,
/// Show only the first N lines of the source. Mutually exclusive with --tail.
#[arg(long = "head", value_name = "N", conflicts_with = "tail")]
pub head: Option<usize>,
/// Render the source as an xxd-style hex dump instead of byte-faithful
/// text. 16 bytes per row, offset prefix, ASCII gutter. Mutually
/// exclusive with parsing- and rendering-oriented flags.
#[arg(
long = "hex",
conflicts_with_all = ["filter", "grep", "prettify", "format", "display", "record_start", "prompt", "preprocess"],
)]
pub hex: bool,
/// Hex characters per group in `--hex` mode. One of 2, 4, 8, 16, 32
/// (default 4, matching `xxd`). 32 means the whole row as a single
/// group with no spacing between hex pairs. Requires `--hex`. Can be
/// changed at runtime with `:hex N`.
#[arg(
long = "hex-group",
value_name = "N",
default_value_t = 4,
requires = "hex",
)]
pub hex_group: usize,
/// Show line numbers.
#[arg(short = 'N', long = "LINE-NUMBERS")]
pub line_numbers: bool,
/// Print available log formats and their named fields, then exit.
#[arg(long = "list-formats")]
pub list_formats: bool,
/// Live mode: re-read the file when its on-disk content changes (mtime,
/// size, or inode). Use this for files rewritten in place — source files
/// being edited, files saved by an editor or AI agent. Different from
/// `--follow` (which watches for *appended* bytes); the two are mutually
/// exclusive. Press `R` inside the pager to force a reload.
#[arg(long = "live", conflicts_with = "follow")]
pub live: bool,
/// Print the full user manual and exit.
#[arg(long = "manual")]
pub manual: bool,
/// Enable mouse capture: click rows in the file picker / help overlay,
/// and scrollwheel scrolls the body. Trade-off: most terminals disable
/// their native text selection while mouse capture is on.
#[arg(long = "mouse")]
pub mouse: bool,
/// Show raw control bytes as `^X` glyphs (pre-0.18 default). Disables
/// SGR / OSC interpretation. Honoured also by the `NO_COLOR` environment
/// variable (any non-empty value) and `CLICOLOR=0`.
#[arg(long = "no-color")]
pub no_color: bool,
/// Ignore $LESSOPEN. Useful when LESSOPEN is exported but not wanted
/// for one invocation.
#[arg(long = "no-preprocess", conflicts_with = "preprocess")]
pub no_preprocess: bool,
/// Non-interactive batch mode: apply --filter / --grep / --head / --tail / --prettify
/// to the source and write the resulting raw bytes to FILE, then exit.
/// Use `-` for stdout (`--stdout` is a synonym). Skips the alt-screen and
/// raw mode entirely. With `--follow`, doesn't exit — keeps appending
/// matching new bytes to FILE as they arrive (Ctrl-C to stop). Not
/// compatible with `--live`.
#[arg(short = 'o', long = "output", value_name = "FILE")]
pub output: Option<String>,
/// Pipe the source file through this command before rendering.
/// Must start with `|`; `%s` is substituted with the file path.
/// Example: `--preprocess '|pdftotext %s -'`. Overrides $LESSOPEN.
#[arg(
long = "preprocess",
value_name = "CMD",
conflicts_with_all = ["no_preprocess", "hex", "follow", "live"],
)]
pub preprocess: Option<String>,
/// Pretty-print structured content (JSON, YAML, TOML, XML, HTML, CSV).
/// Detects the type from the filename extension or the first bytes; use
/// `--content-type=NAME` to override. Static files only — not allowed
/// with `--follow`, `--live`, or `--filter`. Toggle interactively with
/// `Shift-P`; force a type with `-P` then a letter (j/y/t/x/h/c).
#[arg(long = "prettify")]
pub prettify: bool,
/// Replace the hardcoded status format with a templated string.
/// Uses the same `<field>` syntax as `--display`. Available fields:
/// label, top, bottom, total, pct, rec-top, rec-bottom, rec-total,
/// rec-block, wrap-offset, format-tag, filter-tag, grep-tag,
/// hide-tag, search-tag, pretty-tag, live-tag, follow-tag.
/// Per-format default can be set via `prompt = '...'` in formats.toml.
/// Mutually exclusive with --hex.
#[arg(long = "prompt", value_name = "TEMPLATE", conflicts_with = "hex")]
pub prompt: Option<String>,
/// Pass every byte to the terminal raw, including cursor moves and
/// non-SGR escape sequences. Risky: scroll math may break on long lines.
/// Less-style -r. Mutually exclusive with --no-color.
#[arg(short = 'r', long = "raw-control-chars", conflicts_with = "no_color")]
pub raw_control_chars: bool,
/// Treat lines matching REGEX as record boundaries. Lines that don't
/// match are joined to the preceding record. Affects search, filter,
/// grep, and the status line — all operate on whole records when set.
/// Overrides the active --format's record_start if both are present.
/// Without --format, this is the only way to enable records mode for
/// plain text. Example: --record-start '^\['
#[arg(long = "record-start", value_name = "REGEX")]
pub record_start: Option<String>,
/// Synonym for `--output -`: write the batch-mode output to stdout.
#[arg(long = "stdout", conflicts_with = "output")]
pub stdout: bool,
/// Tab stop width (default 8).
#[arg(long = "tab-width", default_value_t = 8)]
pub tab_width: u8,
/// Jump to the tag NAME at startup (requires a tags file).
#[arg(short = 't', long = "tag", value_name = "NAME")]
pub tag: Option<String>,
/// Path to the tags file. Default: walk up from CWD looking for `tags`.
#[arg(short = 'T', long = "tag-file", value_name = "PATH")]
pub tag_file: Option<std::path::PathBuf>,
/// Show only the last N lines of the source. For files this skips most of
/// the index work — useful for huge logs. Combine with `-f` for `tail -f`.
/// Mutually exclusive with --head. Streaming stdin is not supported.
#[arg(long = "tail", value_name = "N", conflicts_with = "head")]
pub tail: Option<usize>,
/// Files to view (only the first is opened in MVP).
pub files: Vec<PathBuf>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_no_flags_no_files() {
let a = Args::parse_from(["tess"]);
assert!(!a.line_numbers);
assert!(!a.chop);
assert_eq!(a.tab_width, 8);
assert!(a.files.is_empty());
}
#[test]
fn parses_short_flags_and_file() {
let a = Args::parse_from(["tess", "-N", "-S", "foo.txt"]);
assert!(a.line_numbers);
assert!(a.chop);
assert_eq!(a.files, vec![PathBuf::from("foo.txt")]);
}
#[test]
fn parses_tab_width() {
let a = Args::parse_from(["tess", "--tab-width", "4", "x"]);
assert_eq!(a.tab_width, 4);
}
#[test]
fn collects_multiple_files() {
let a = Args::parse_from(["tess", "a", "b", "c"]);
assert_eq!(a.files.len(), 3);
}
#[test]
fn parses_follow_short_flag() {
let a = Args::parse_from(["tess", "-f", "log.txt"]);
assert!(a.follow);
assert_eq!(a.files, vec![PathBuf::from("log.txt")]);
}
#[test]
fn parses_follow_long_flag() {
let a = Args::parse_from(["tess", "--follow"]);
assert!(a.follow);
}
#[test]
fn follow_defaults_off() {
let a = Args::parse_from(["tess", "x"]);
assert!(!a.follow);
}
#[test]
fn parses_head() {
let a = Args::parse_from(["tess", "--head", "100", "x"]);
assert_eq!(a.head, Some(100));
assert_eq!(a.tail, None);
}
#[test]
fn parses_tail() {
let a = Args::parse_from(["tess", "--tail", "50", "x"]);
assert_eq!(a.tail, Some(50));
assert_eq!(a.head, None);
}
#[test]
fn head_and_tail_are_mutually_exclusive() {
let r = Args::try_parse_from(["tess", "--head", "10", "--tail", "20", "x"]);
assert!(r.is_err(), "clap should reject combining --head and --tail");
}
#[test]
fn head_tail_default_to_none() {
let a = Args::parse_from(["tess", "x"]);
assert!(a.head.is_none());
assert!(a.tail.is_none());
}
#[test]
fn parses_grep_repeatable_and_no_format_required() {
let a = Args::parse_from([
"tess",
"--grep", "error",
"--grep", r"^\[",
"log",
]);
assert_eq!(a.grep.len(), 2);
assert_eq!(a.grep[0], "error");
assert_eq!(a.grep[1], r"^\[");
assert_eq!(a.format, None);
}
#[test]
fn parses_format_and_filter() {
let a = Args::parse_from([
"tess", "--format", "apache-combined",
"--filter", "status=500",
"--filter", "ip~^10\\.",
"log",
]);
assert_eq!(a.format.as_deref(), Some("apache-combined"));
assert_eq!(a.filter.len(), 2);
assert_eq!(a.filter[0], "status=500");
}
#[test]
fn parses_dim() {
let a = Args::parse_from(["tess", "--format", "x", "--filter", "y=z", "--dim", "f"]);
assert!(a.dim);
}
#[test]
fn parses_list_formats() {
let a = Args::parse_from(["tess", "--list-formats"]);
assert!(a.list_formats);
}
#[test]
fn parses_manual() {
let a = Args::parse_from(["tess", "--manual"]);
assert!(a.manual);
}
#[test]
fn parses_examples() {
let a = Args::parse_from(["tess", "--examples"]);
assert!(a.examples);
}
#[test]
fn parses_live() {
let a = Args::parse_from(["tess", "--live", "f"]);
assert!(a.live);
assert!(!a.follow);
}
#[test]
fn live_and_follow_are_mutually_exclusive() {
let r = Args::try_parse_from(["tess", "--live", "--follow", "f"]);
assert!(r.is_err(), "clap should reject combining --live and --follow");
}
#[test]
fn parses_prettify() {
let a = Args::parse_from(["tess", "--prettify", "f.json"]);
assert!(a.prettify);
assert_eq!(a.content_type, None);
}
#[test]
fn parses_content_type() {
let a = Args::parse_from(["tess", "--content-type", "json", "f"]);
assert_eq!(a.content_type.as_deref(), Some("json"));
}
#[test]
fn parses_output_long_and_short() {
let a = Args::parse_from(["tess", "-o", "/tmp/out.txt", "f"]);
assert_eq!(a.output.as_deref(), Some("/tmp/out.txt"));
let b = Args::parse_from(["tess", "--output", "/tmp/out.txt", "f"]);
assert_eq!(b.output.as_deref(), Some("/tmp/out.txt"));
}
#[test]
fn parses_stdout_flag() {
let a = Args::parse_from(["tess", "--stdout", "f"]);
assert!(a.stdout);
assert_eq!(a.output, None);
}
#[test]
fn output_and_stdout_are_mutually_exclusive() {
let r = Args::try_parse_from(["tess", "-o", "x", "--stdout", "f"]);
assert!(r.is_err(), "clap should reject combining --output and --stdout");
}
#[test]
fn parses_mouse_flag() {
let a = Args::parse_from(["tess", "--mouse", "f"]);
assert!(a.mouse);
}
#[test]
fn mouse_defaults_off() {
let a = Args::parse_from(["tess", "f"]);
assert!(!a.mouse);
}
#[test]
fn help_lists_flags_in_alphabetical_order() {
use clap::CommandFactory;
let mut cmd = Args::command();
let help = cmd.render_help().to_string();
let expected = [
"--chop-long-lines",
"--content-type",
"--dim",
"--display",
"--examples",
"--filter",
"--follow",
"--format",
"--grep",
"--head",
"--hex",
"--hex-group",
"--LINE-NUMBERS",
"--list-formats",
"--live",
"--manual",
"--mouse",
"--no-color",
"--no-preprocess",
"--output",
"--preprocess",
"--prettify",
"--prompt",
"--raw-control-chars",
"--record-start",
"--stdout",
"--tab-width",
"--tag",
"--tag-file",
"--tail",
];
let listed: Vec<&str> = help
.lines()
.map(str::trim_start)
.filter(|l| l.starts_with('-'))
.filter_map(|l| {
l.split(|c: char| c.is_whitespace() || c == ',')
.find(|tok| expected.contains(tok))
})
.collect();
assert_eq!(listed, expected, "help long-flag order should be alphabetical");
}
}