17 Commits

Author SHA1 Message Date
ca6fca760d oci: Use Centos Stream rolling image 2026-06-09 19:45:17 +03:00
669260ba98 oci: Use UBI10 image 2026-06-09 19:26:00 +03:00
62e727734a build: Change target name 2026-06-09 19:25:30 +03:00
f6db68fac6 doc: Update run cmd and credits 2026-06-09 18:50:33 +03:00
7531cdf59f oci: Create Containerfile 2026-06-09 18:43:59 +03:00
fabfbc52fd doc: Update readme 2026-06-09 18:40:33 +03:00
74af7639be edit: Add line deletion shortcut 2026-06-09 18:16:37 +03:00
a7813a851c Make delete key work 2026-06-09 18:06:44 +03:00
e83cab94b0 Add line numbers in the editor 2026-06-09 18:05:42 +03:00
7e378ada8b Few explanations how the game works 2026-05-22 00:04:06 +03:00
0749cc5003 Demonolithify tests 2026-05-21 23:59:16 +03:00
db124eeb97 Split tests per level 2026-05-21 23:56:03 +03:00
cb326d432f Fix level tests 2026-05-21 23:47:24 +03:00
cd3d3395c5 Update screenshot 2026-05-21 23:37:35 +03:00
250c326c92 Add all levels 2026-05-21 23:37:19 +03:00
abc0fa7784 Add level 11: Advanced Anchors
`shapes:` list defines 2-3 polygons (name + sides + interior angle sum);
`copies:` is a list of 3-4 selections (with possible repetition) drawn
from the same pool. serde_yaml expands aliases on parse, so the target
is the inlined form; players using `- &name` anchors inside the list
and `*name` aliases in `copies:` produce the same Value and pass via
the semantic short-circuit.

All randomised per seed (ChaCha8Rng XOR'd with 0x..0B).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:17:44 +03:00
9f8e5caaa8 Add level 11: Advanced Anchors
`shapes:` list defines 2-3 polygons (name + sides + interior angle sum);
`copies:` is a list of 3-4 selections (with possible repetition) drawn
from the same pool. serde_yaml expands aliases on parse, so the target
is the inlined form; players using `- &name` anchors inside the list
and `*name` aliases in `copies:` produce the same Value and pass via
the semantic short-circuit.

All randomised per seed (ChaCha8Rng XOR'd with 0x..0B).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:59:44 +03:00
10 changed files with 487 additions and 44 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
target
.git
.gameplay
*.md
screenshot.png

View File

@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[[bin]] [[bin]]
name = "go" name = "yamlabyrinth"
path = "src/bin/go.rs" path = "src/bin/go.rs"
[lib] [lib]

11
Containerfile Normal file
View File

@@ -0,0 +1,11 @@
FROM docker.io/library/rust:1-slim AS builder
WORKDIR /src
COPY Cargo.toml Cargo.lock ./
COPY src ./src
RUN cargo build --release --bin yamlabyrinth
FROM quay.io/centos/centos:stream10-minimal
COPY --from=builder /src/target/release/yamlabyrinth /usr/local/bin/yamlabyrinth
USER nobody
WORKDIR /tmp
ENTRYPOINT ["yamlabyrinth"]

View File

@@ -2,8 +2,26 @@
A text dungeon game that teaches you YAML. A text dungeon game that teaches you YAML.
The game uses actual YAML parsing libraries and generates semi-random levels
by describing a secret YAML file that the user has to recreate in the editor.
There are 11 levels in the game, so if you're on level 12, you won the game!
![screenshot](screenshot.png) ![screenshot](screenshot.png)
## How to start: ## How to start:
cargo run cargo run --release
## How to start (container):
docker run -it --rm quay.io/kareiva/yamlabyrinth:latest
## LLM Notice
This was a fun project to do while learning Rust syntax and pecularities. I
have mostly used Opus 4.7 with 1M context to assist me with coding.
## Author
Simonas Kareiva <skareiva@redhat.com>, <simonas@5grupe.lt>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

After

Width:  |  Height:  |  Size: 72 KiB

View File

@@ -112,14 +112,16 @@ impl Level for Complex {
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping"); serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new(); let mut d = Describer::new();
// No tab characters: ratatui's Paragraph renders tabs unevenly,
// which combined with the typewriter's progressive reveal can
// produce overlapping characters. Use plain spaces for indents.
d.register( d.register(
"l07", "l07",
"Floor {{ floor }}.\n\ "Floor {{ floor }}.\n\n\
{% for r in rooms %}\n\ {% for r in rooms %}{{ r.name }} — a {{ r.kind }} (locked: {{ r.locked }})\n\
{{ r.name }} — a {{ r.kind }} (locked: {{ r.locked }})\n\ exits: {% for e in r.exits %}{{ e }}{% if not loop.last %}, {% endif %}{% endfor %}\n\
\texits: {% for e in r.exits %}{{ e }}{% if not loop.last %}, {% endif %}{% endfor %}\n\ contents: {% for c in r.contents %}{{ c }}{% if not loop.last %}, {% endif %}{% endfor %}\n\n\
\tcontents: {% for c in r.contents %}{{ c }}{% if not loop.last %}, {% endif %}{% endfor %}\n\ {% endfor %}\
{% endfor %}\n\
💡 Combine maps, lists, and scalars — `floor:` is an int, each room is a dict with two lists.", 💡 Combine maps, lists, and scalars — `floor:` is an int, each room is a dict with two lists.",
) )
.expect("register template"); .expect("register template");

View File

@@ -0,0 +1,141 @@
//! Level 11 — advanced anchors. Anchor shapes inside a list, alias
//! them elsewhere.
//!
//! Paired design note: `l11.md`.
//!
//! Like L6, serde_yaml expands aliases on parse, so the emitted target
//! is the fully-inlined form. Players who use `&anchor` / `*alias`
//! produce the same `Value` and pass via the semantic short-circuit.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Sequence, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct AdvAnchors;
const SHAPES: &[(&str, i64)] = &[
("triangle", 3),
("square", 4),
("pentagon", 5),
("hexagon", 6),
("heptagon", 7),
("octagon", 8),
];
#[derive(Serialize)]
struct DescCtx {
shapes: Vec<ShapeDesc>,
copies: Vec<String>,
}
#[derive(Serialize)]
struct ShapeDesc {
name: String,
sides: i64,
interior_angle_sum: i64,
}
fn shape_value(name: &str, sides: i64) -> Value {
let mut m = Mapping::new();
m.insert(
Value::String("name".to_string()),
Value::String(name.to_string()),
);
m.insert(Value::String("sides".to_string()), Value::from(sides));
m.insert(
Value::String("interior".to_string()),
Value::from((sides - 2) * 180),
);
Value::Mapping(m)
}
impl Level for AdvAnchors {
fn id(&self) -> u8 {
11
}
fn name(&self) -> &'static str {
"Advanced Anchors"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_000B);
let n = rng.gen_range(2..=3);
let picked: Vec<(&'static str, i64)> = SHAPES
.choose_multiple(&mut rng, n)
.copied()
.collect();
// The defining `shapes:` list.
let shapes_seq: Sequence = picked
.iter()
.map(|(name, sides)| shape_value(name, *sides))
.collect();
// `copies:` — random selections with possible repetition.
let m = rng.gen_range(3..=4);
let mut copies_seq = Sequence::new();
let mut copy_names = Vec::new();
for _ in 0..m {
let (name, sides) = picked.choose(&mut rng).unwrap();
copies_seq.push(shape_value(name, *sides));
copy_names.push((*name).to_string());
}
let mut top = Mapping::new();
top.insert(
Value::String("shapes".to_string()),
Value::Sequence(shapes_seq),
);
top.insert(
Value::String("copies".to_string()),
Value::Sequence(copies_seq),
);
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let shape_descs: Vec<ShapeDesc> = picked
.iter()
.map(|(name, sides)| ShapeDesc {
name: (*name).to_string(),
sides: *sides,
interior_angle_sum: (sides - 2) * 180,
})
.collect();
let mut d = Describer::new();
d.register(
"l11",
"Shapes are defined once and reused.\n\
Definitions:\n\
{% for s in shapes %}- {{ s.name }}: sides={{ s.sides }}, interior={{ s.interior_angle_sum }}\n\
{% endfor %}\n\
Copies, in order: {% for c in copies %}{{ c }}{% if not loop.last %}, {% endif %}{% endfor %}\n\
💡 Anchor each shape in the list with `- &name`, then alias by `*name` in copies.",
)
.expect("register template");
let description = d
.render(
"l11",
&DescCtx {
shapes: shape_descs,
copies: copy_names,
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🔺 The geometry chamber repeats its forms.".to_string(),
}
}
}

View File

@@ -20,6 +20,7 @@ pub mod l07_complex;
pub mod l08_tags; pub mod l08_tags;
pub mod l09_operators; pub mod l09_operators;
pub mod l10_dynamic; pub mod l10_dynamic;
pub mod l11_adv_anchors;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -92,5 +93,11 @@ pub fn registry() -> Vec<Box<dyn Level>> {
Box::new(l03_dict::Dict), Box::new(l03_dict::Dict),
Box::new(l04_list::List), Box::new(l04_list::List),
Box::new(l05_dict_list::DictList), Box::new(l05_dict_list::DictList),
Box::new(l06_anchors::Anchors),
Box::new(l07_complex::Complex),
Box::new(l08_tags::Tags),
Box::new(l09_operators::Operators),
Box::new(l10_dynamic::Dynamic),
Box::new(l11_adv_anchors::AdvAnchors),
] ]
} }

View File

@@ -81,50 +81,246 @@ mod smoke {
assert_eq!(loaded.current_seed, p.current_seed); assert_eq!(loaded.current_seed, p.current_seed);
} }
#[test] // ---- Per-level tests --------------------------------------------
fn levels_generate_canonical_yaml() { //
let registry = levels::registry(); // One test per level. `checked_level` runs the invariants every
assert_eq!(registry.len(), 3); // level must satisfy (correct id, valid & deterministic canonical
// YAML, self-similarity 1.0); each test then pins the *shape* its
// design note promises and, where it is the whole lesson, the
// semantic forgiveness.
// Level 1: any null-equivalent passes via the semantic short-circuit. /// Look up a string key in a YAML mapping, panicking with a clear
let g1 = registry[0].generate(0); /// message if it is missing — keeps the per-level assertions terse.
let parsed: serde_yaml::Value = serde_yaml::from_str(&g1.target_yaml).unwrap(); fn field<'a>(v: &'a Value, key: &str) -> &'a Value {
assert!(parsed.is_null()); v.get(key)
.unwrap_or_else(|| panic!("expected key `{key}` in {v:?}"))
}
/// Parse a target YAML string, asserting it is well-formed.
fn parse(yaml: &str) -> Value {
serde_yaml::from_str(yaml).expect("target is valid YAML")
}
/// Generate level `index` (0-based) with `seed`, assert the invariants
/// every level must satisfy, and return its output for shape checks:
/// - the level reports `id == index + 1`,
/// - the target is valid YAML,
/// - generation is deterministic for a given seed,
/// - the canonical target scores 1.0 against itself.
fn checked_level(index: usize, seed: u64) -> levels::Generated {
let registry = levels::registry();
let level = &registry[index];
let want_id = index as u8 + 1;
assert_eq!( assert_eq!(
similarity::semantic_or_textual(&g1.target_yaml, "---"), level.id(),
want_id,
"registry index {index} must hold level {want_id}"
);
let g = level.generate(seed);
serde_yaml::from_str::<Value>(&g.target_yaml)
.unwrap_or_else(|e| panic!("level {want_id} target is not valid YAML: {e}"));
let again = level.generate(seed);
assert_eq!(
g.target_yaml, again.target_yaml,
"level {want_id} must be deterministic for a given seed"
);
assert_eq!(
similarity::semantic_or_textual(&g.target_yaml, &g.target_yaml),
1.0,
"level {want_id} target must score 1.0 against itself"
);
g
}
#[test]
fn registry_lists_all_eleven_levels() {
assert_eq!(
levels::registry().len(),
11,
"all 11 levels must be registered"
);
}
#[test]
fn level_01_minimum_is_a_null_document() {
// Any null-equivalent passes via the semantic short-circuit.
let g = checked_level(0, 0);
assert!(parse(&g.target_yaml).is_null(), "the minimum YAML is null");
assert_eq!(
similarity::semantic_or_textual(&g.target_yaml, "---"),
1.0, 1.0,
"`---` should be accepted as the minimum YAML" "`---` should be accepted as the minimum YAML"
); );
assert_eq!( assert_eq!(
similarity::semantic_or_textual(&g1.target_yaml, "null"), similarity::semantic_or_textual(&g.target_yaml, "null"),
1.0 1.0,
"`null` should be accepted as the minimum YAML"
); );
}
// Level 2: deterministic per seed, non-empty mapping. #[test]
let g2 = registry[1].generate(42); fn level_02_key_value_is_a_non_empty_mapping() {
let v2: serde_yaml::Value = serde_yaml::from_str(&g2.target_yaml).unwrap(); let g = checked_level(1, 42);
let m = v2.as_mapping().expect("level 2 produces a mapping"); let v = parse(&g.target_yaml);
assert!(!m.is_empty()); assert!(
let g2_again = registry[1].generate(42); !v.as_mapping()
assert_eq!( .expect("level 2 produces a mapping")
g2.target_yaml, g2_again.target_yaml, .is_empty(),
"same seed should produce the same target" "level 2 yields a non-empty mapping"
); );
}
// Level 3: deterministic per seed; produces a mapping of mappings, #[test]
// each inner mapping has a `type` key. fn level_03_dict_nests_typed_mappings() {
let g3 = registry[2].generate(123); // A mapping of mappings; each inner mapping carries a `type` key.
let v3: serde_yaml::Value = serde_yaml::from_str(&g3.target_yaml).unwrap(); let g = checked_level(2, 123);
let m3 = v3.as_mapping().expect("level 3 produces a mapping"); let v = parse(&g.target_yaml);
assert!(!m3.is_empty()); let m = v.as_mapping().expect("level 3 produces a mapping");
for (_dir, feature) in m3 { assert!(!m.is_empty(), "at least one direction");
let inner = feature.as_mapping().expect("level 3 inner is a mapping"); for (_dir, feature) in m {
feature.as_mapping().expect("level 3 inner is a mapping");
assert!( assert!(
inner.get(serde_yaml::Value::String("type".into())).is_some(), feature.get("type").is_some(),
"each direction must carry a `type` key" "each direction must carry a `type` key"
); );
} }
let g3_again = registry[2].generate(123); }
assert_eq!(g3.target_yaml, g3_again.target_yaml);
#[test]
fn level_04_chest_is_a_list() {
// `chest:` is a list of 35 item strings.
let v = parse(&checked_level(3, 4).target_yaml);
let chest = field(&v, "chest").as_sequence().expect("chest is a list");
assert!((3..=5).contains(&chest.len()), "chest holds 35 items");
assert!(chest.iter().all(Value::is_string), "every item is a string");
}
#[test]
fn level_05_chambers_is_a_dict_of_lists() {
// `chambers:` is a dict of 23 lists, 23 items each.
let v = parse(&checked_level(4, 5).target_yaml);
let chambers = field(&v, "chambers")
.as_mapping()
.expect("chambers is a dict");
assert!((2..=3).contains(&chambers.len()), "23 chambers");
for (_name, items) in chambers {
let items = items.as_sequence().expect("each chamber holds a list");
assert!((2..=3).contains(&items.len()), "23 items per chamber");
}
}
#[test]
fn level_06_trap_repeats_in_every_room() {
// `trap:` is defined once; every room repeats it verbatim, so a
// player using `&anchor`/`*alias` parses to the same Value.
let v = parse(&checked_level(5, 6).target_yaml);
let trap = field(&v, "trap");
for key in ["type", "depth", "spikes"] {
assert!(trap.get(key).is_some(), "trap carries `{key}`");
}
let rooms = field(&v, "rooms").as_mapping().expect("rooms is a dict");
assert!(!rooms.is_empty(), "at least one room");
for (_room, payload) in rooms {
assert_eq!(payload, trap, "every room repeats the trap definition");
}
}
#[test]
fn level_07_floor_map_nests_maps_and_lists() {
// `floor:` int + `rooms:` dict; each room nests two lists.
let v = parse(&checked_level(6, 7).target_yaml);
assert!(field(&v, "floor").is_i64(), "floor is an integer");
let rooms = field(&v, "rooms").as_mapping().expect("rooms is a dict");
assert!(!rooms.is_empty(), "at least one room");
for (_name, room) in rooms {
assert!(field(room, "type").is_string(), "room.type is a string");
assert!(field(room, "locked").is_bool(), "room.locked is a bool");
assert!(field(room, "exits").is_sequence(), "room.exits is a list");
assert!(
field(room, "contents").is_sequence(),
"room.contents is a list"
);
}
}
#[test]
fn level_08_scroll_keeps_explicit_types() {
// Explicit types: a multi-line string, a float, and a digit-only
// string that must NOT collapse to an integer.
let v = parse(&checked_level(7, 8).target_yaml);
let scroll = field(&v, "scroll").as_str().expect("scroll is a string");
assert!(scroll.contains('\n'), "scroll preserves its newlines");
assert!(field(&v, "weight").is_f64(), "weight is a float");
let title = field(&v, "title");
assert!(title.is_string(), "title stays a string, not an int");
assert!(
title.as_str().unwrap().chars().all(|c| c.is_ascii_digit()),
"title is digit-only — the point of the `!!str` lesson"
);
}
#[test]
fn level_09_doors_merge_shared_defaults() {
// Merge keys: each door carries a literal `<<` whose value is the
// shared defaults dict, plus its own override.
let v = parse(&checked_level(8, 9).target_yaml);
let defaults = field(&v, "door_defaults");
for door in ["north_door", "south_door"] {
assert_eq!(
field(field(&v, door), "<<"),
defaults,
"{door} merges the shared defaults via `<<`"
);
}
assert!(field(field(&v, "north_door"), "locked").is_bool());
assert!(field(field(&v, "south_door"), "material").is_string());
}
#[test]
fn level_10_ledger_forgives_numeric_forms() {
// The ledger: int gold/silver, float experience, ISO date. The
// lesson is numeric forgiveness, so hex must score a perfect match.
let g = checked_level(9, 10);
let v = parse(&g.target_yaml);
let vault = field(&v, "vault");
let gold = field(vault, "gold").as_i64().expect("gold is an integer");
assert!(field(vault, "silver").is_i64(), "silver is an integer");
assert!(field(vault, "experience").is_f64(), "experience is a float");
assert!(field(vault, "date").is_string(), "date is an ISO string");
let hex_candidate = g
.target_yaml
.replace(&format!("gold: {gold}"), &format!("gold: 0x{gold:X}"));
assert_ne!(hex_candidate, g.target_yaml, "hex rewrite must apply");
assert_eq!(
similarity::semantic_or_textual(&g.target_yaml, &hex_candidate),
1.0,
"writing gold in hex must still score a perfect match"
);
}
#[test]
fn level_11_copies_alias_defined_shapes() {
// `shapes:` defines polygons; `copies:` reuses them, so each copy
// is structurally identical to one of the definitions.
let v = parse(&checked_level(10, 11).target_yaml);
let shapes = field(&v, "shapes").as_sequence().expect("shapes is a list");
assert!((2..=3).contains(&shapes.len()), "23 defined shapes");
for s in shapes {
assert!(field(s, "name").is_string(), "shape.name is a string");
let sides = field(s, "sides").as_i64().expect("shape.sides is an int");
assert_eq!(
field(s, "interior").as_i64().expect("shape.interior is an int"),
(sides - 2) * 180,
"interior angle sum follows (n-2)·180"
);
}
let copies = field(&v, "copies").as_sequence().expect("copies is a list");
assert!((3..=4).contains(&copies.len()), "34 copies");
for c in copies {
assert!(shapes.contains(c), "every copy aliases a defined shape");
}
} }
} }

View File

@@ -180,6 +180,30 @@ impl Editor {
} }
} }
fn delete(&mut self) {
let (r, col) = self.cursor;
let line_len = self.buffer[r].len();
if col < line_len {
self.buffer[r].remove(col);
} else if r + 1 < self.buffer.len() {
let next = self.buffer.remove(r + 1);
self.buffer[r].push_str(&next);
}
}
fn delete_line(&mut self) {
let (r, _) = self.cursor;
if self.buffer.len() == 1 {
self.buffer[0].clear();
self.cursor = (0, 0);
} else {
self.buffer.remove(r);
let new_r = r.min(self.buffer.len() - 1);
let new_col = self.cursor.1.min(self.buffer[new_r].len());
self.cursor = (new_r, new_col);
}
}
fn newline(&mut self) { fn newline(&mut self) {
let (r, col) = self.cursor; let (r, col) = self.cursor;
let col = col.min(self.buffer[r].len()); let col = col.min(self.buffer[r].len());
@@ -477,8 +501,10 @@ fn step(
// Editor focus inside Game: dispatch editing keys. // Editor focus inside Game: dispatch editing keys.
if *focus == Focus::Editor && matches!(screen, Screen::Game) { if *focus == Focus::Editor && matches!(screen, Screen::Game) {
match key.code { match key.code {
KeyCode::Char('k') if ctrl => editor.delete_line(),
KeyCode::Char(c) if !ctrl => editor.insert_char(c), KeyCode::Char(c) if !ctrl => editor.insert_char(c),
KeyCode::Backspace => editor.backspace(), KeyCode::Backspace => editor.backspace(),
KeyCode::Delete => editor.delete(),
KeyCode::Enter => editor.newline(), KeyCode::Enter => editor.newline(),
KeyCode::Left => editor.left(), KeyCode::Left => editor.left(),
KeyCode::Right => editor.right(), KeyCode::Right => editor.right(),
@@ -695,6 +721,7 @@ fn help_widget<'a>() -> Paragraph<'a> {
\n\ \n\
[Tab] swap focus between log and editor\n\ [Tab] swap focus between log and editor\n\
[Ctrl-X] grade your YAML\n\ [Ctrl-X] grade your YAML\n\
[Ctrl-K] delete current line (in editor)\n\
[Ctrl-H] open this help\n\ [Ctrl-H] open this help\n\
[Esc] close help · or focus log when editing\n\ [Esc] close help · or focus log when editing\n\
[↑/↓] scroll the log (when log is focused)\n\ [↑/↓] scroll the log (when log is focused)\n\
@@ -968,6 +995,11 @@ fn render_editor(frame: &mut Frame, area: Rect, editor: &Editor, focused: bool)
}; };
let block = Block::default().borders(Borders::ALL).title(title); let block = Block::default().borders(Borders::ALL).title(title);
// Line numbers occupy a fixed-width left gutter. Width grows with the
// largest line number so the body never shifts as lines are added.
let gutter_width = line_number_width(editor.buffer.len());
let gutter_style = Style::default().fg(Color::DarkGray);
if focused { if focused {
// Highlight the character under the cursor with explicit bg + fg // Highlight the character under the cursor with explicit bg + fg
// colours (not `REVERSED`) so the cursor cell is filled even when // colours (not `REVERSED`) so the cursor cell is filled even when
@@ -981,24 +1013,55 @@ fn render_editor(frame: &mut Frame, area: Rect, editor: &Editor, focused: bool)
.iter() .iter()
.enumerate() .enumerate()
.map(|(r, line)| { .map(|(r, line)| {
if r == cr { let body = if r == cr {
editor_cursor_line(line, cc, cursor_style) editor_cursor_line(line, cc, cursor_style)
} else { } else {
Line::from(line.clone()) Line::from(line.clone())
} };
prepend_line_number(body, r + 1, gutter_width, gutter_style)
}) })
.collect(); .collect();
let p = Paragraph::new(lines).block(block).wrap(Wrap { trim: false }); let p = Paragraph::new(lines).block(block).wrap(Wrap { trim: false });
frame.render_widget(p, area); frame.render_widget(p, area);
} else { } else {
let p = Paragraph::new(editor.text()) let lines: Vec<Line> = editor
.block(block) .buffer
.wrap(Wrap { trim: false }); .iter()
.enumerate()
.map(|(r, line)| {
prepend_line_number(
Line::from(line.clone()),
r + 1,
gutter_width,
gutter_style,
)
})
.collect();
let p = Paragraph::new(lines).block(block).wrap(Wrap { trim: false });
frame.render_widget(p, area); frame.render_widget(p, area);
} }
} }
fn line_number_width(line_count: usize) -> usize {
let max = line_count.max(1);
let mut digits = 1;
let mut n = max;
while n >= 10 {
n /= 10;
digits += 1;
}
digits
}
fn prepend_line_number(line: Line<'static>, number: usize, width: usize, style: Style) -> Line<'static> {
let gutter = format!("{:>width$}", number, width = width);
let mut spans = Vec::with_capacity(line.spans.len() + 1);
spans.push(Span::styled(gutter, style));
spans.extend(line.spans);
Line::from(spans)
}
/// Build the cursor-bearing line as three spans: text before, the /// Build the cursor-bearing line as three spans: text before, the
/// highlighted character at the cursor, text after. If the cursor sits /// highlighted character at the cursor, text after. If the cursor sits
/// past the end of the line (or on a whitespace cell), the highlight /// past the end of the line (or on a whitespace cell), the highlight