Compare commits
11 Commits
db124eeb97
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| ca6fca760d | |||
| 669260ba98 | |||
| 62e727734a | |||
| f6db68fac6 | |||
| 7531cdf59f | |||
| fabfbc52fd | |||
| 74af7639be | |||
| a7813a851c | |||
| e83cab94b0 | |||
| 7e378ada8b | |||
| 0749cc5003 |
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
target
|
||||||
|
.git
|
||||||
|
.gameplay
|
||||||
|
*.md
|
||||||
|
screenshot.png
|
||||||
@@ -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
11
Containerfile
Normal 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"]
|
||||||
20
README.md
20
README.md
@@ -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!
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## 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>
|
||||||
|
|||||||
190
src/lib.rs
190
src/lib.rs
@@ -81,82 +81,13 @@ 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();
|
|
||||||
assert_eq!(registry.len(), 11, "all 11 levels must be registered");
|
|
||||||
|
|
||||||
// Invariants every level must satisfy, regardless of how it generates.
|
|
||||||
for (i, level) in registry.iter().enumerate() {
|
|
||||||
let want_id = i as u8 + 1;
|
|
||||||
assert_eq!(
|
|
||||||
level.id(),
|
|
||||||
want_id,
|
|
||||||
"level at registry index {i} must report id {want_id}"
|
|
||||||
);
|
|
||||||
|
|
||||||
let seed = 0x5EED_0000 + i as u64;
|
|
||||||
let g = level.generate(seed);
|
|
||||||
|
|
||||||
// The target must be valid YAML.
|
|
||||||
serde_yaml::from_str::<serde_yaml::Value>(&g.target_yaml)
|
|
||||||
.unwrap_or_else(|e| panic!("level {want_id} target is not valid YAML: {e}"));
|
|
||||||
|
|
||||||
// Generation is deterministic for a given seed.
|
|
||||||
let again = level.generate(seed);
|
|
||||||
assert_eq!(
|
|
||||||
g.target_yaml, again.target_yaml,
|
|
||||||
"level {want_id} must be deterministic for a given seed"
|
|
||||||
);
|
|
||||||
|
|
||||||
// The canonical target must be a perfect match against itself.
|
|
||||||
assert_eq!(
|
|
||||||
similarity::semantic_or_textual(&g.target_yaml, &g.target_yaml),
|
|
||||||
1.0,
|
|
||||||
"level {want_id} target must score 1.0 against itself"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Level 1: any null-equivalent passes via the semantic short-circuit.
|
|
||||||
let g1 = registry[0].generate(0);
|
|
||||||
let parsed: serde_yaml::Value = serde_yaml::from_str(&g1.target_yaml).unwrap();
|
|
||||||
assert!(parsed.is_null());
|
|
||||||
assert_eq!(
|
|
||||||
similarity::semantic_or_textual(&g1.target_yaml, "---"),
|
|
||||||
1.0,
|
|
||||||
"`---` should be accepted as the minimum YAML"
|
|
||||||
);
|
|
||||||
assert_eq!(similarity::semantic_or_textual(&g1.target_yaml, "null"), 1.0);
|
|
||||||
|
|
||||||
// Level 2: non-empty mapping.
|
|
||||||
let g2 = registry[1].generate(42);
|
|
||||||
let v2: serde_yaml::Value = serde_yaml::from_str(&g2.target_yaml).unwrap();
|
|
||||||
assert!(!v2
|
|
||||||
.as_mapping()
|
|
||||||
.expect("level 2 produces a mapping")
|
|
||||||
.is_empty());
|
|
||||||
|
|
||||||
// Level 3: a mapping of mappings; each inner mapping has a `type` key.
|
|
||||||
let g3 = registry[2].generate(123);
|
|
||||||
let v3: serde_yaml::Value = serde_yaml::from_str(&g3.target_yaml).unwrap();
|
|
||||||
let m3 = v3.as_mapping().expect("level 3 produces a mapping");
|
|
||||||
assert!(!m3.is_empty());
|
|
||||||
for (_dir, feature) in m3 {
|
|
||||||
let inner = feature.as_mapping().expect("level 3 inner is a mapping");
|
|
||||||
assert!(
|
|
||||||
inner.get(serde_yaml::Value::String("type".into())).is_some(),
|
|
||||||
"each direction must carry a `type` key"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Per-level shape checks -------------------------------------
|
|
||||||
//
|
//
|
||||||
// One test per level. Each pins the *shape* its design note promises
|
// One test per level. `checked_level` runs the invariants every
|
||||||
// and, where it is the whole lesson, the semantic forgiveness. The
|
// level must satisfy (correct id, valid & deterministic canonical
|
||||||
// generic invariants (valid YAML, determinism, self-similarity, id
|
// YAML, self-similarity 1.0); each test then pins the *shape* its
|
||||||
// ordering) are covered once for every level by
|
// design note promises and, where it is the whole lesson, the
|
||||||
// `levels_generate_canonical_yaml` above.
|
// semantic forgiveness.
|
||||||
|
|
||||||
/// Look up a string key in a YAML mapping, panicking with a clear
|
/// Look up a string key in a YAML mapping, panicking with a clear
|
||||||
/// message if it is missing — keeps the per-level assertions terse.
|
/// message if it is missing — keeps the per-level assertions terse.
|
||||||
@@ -165,20 +96,103 @@ mod smoke {
|
|||||||
.unwrap_or_else(|| panic!("expected key `{key}` in {v:?}"))
|
.unwrap_or_else(|| panic!("expected key `{key}` in {v:?}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generate level `index` (0-based) with the given seed.
|
|
||||||
fn gen_level(index: usize, seed: u64) -> levels::Generated {
|
|
||||||
levels::registry()[index].generate(seed)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parse a target YAML string, asserting it is well-formed.
|
/// Parse a target YAML string, asserting it is well-formed.
|
||||||
fn parse(yaml: &str) -> Value {
|
fn parse(yaml: &str) -> Value {
|
||||||
serde_yaml::from_str(yaml).expect("target is valid YAML")
|
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 = ®istry[index];
|
||||||
|
let want_id = index as u8 + 1;
|
||||||
|
assert_eq!(
|
||||||
|
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,
|
||||||
|
"`---` should be accepted as the minimum YAML"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
similarity::semantic_or_textual(&g.target_yaml, "null"),
|
||||||
|
1.0,
|
||||||
|
"`null` should be accepted as the minimum YAML"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn level_02_key_value_is_a_non_empty_mapping() {
|
||||||
|
let g = checked_level(1, 42);
|
||||||
|
let v = parse(&g.target_yaml);
|
||||||
|
assert!(
|
||||||
|
!v.as_mapping()
|
||||||
|
.expect("level 2 produces a mapping")
|
||||||
|
.is_empty(),
|
||||||
|
"level 2 yields a non-empty mapping"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn level_03_dict_nests_typed_mappings() {
|
||||||
|
// A mapping of mappings; each inner mapping carries a `type` key.
|
||||||
|
let g = checked_level(2, 123);
|
||||||
|
let v = parse(&g.target_yaml);
|
||||||
|
let m = v.as_mapping().expect("level 3 produces a mapping");
|
||||||
|
assert!(!m.is_empty(), "at least one direction");
|
||||||
|
for (_dir, feature) in m {
|
||||||
|
feature.as_mapping().expect("level 3 inner is a mapping");
|
||||||
|
assert!(
|
||||||
|
feature.get("type").is_some(),
|
||||||
|
"each direction must carry a `type` key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn level_04_chest_is_a_list() {
|
fn level_04_chest_is_a_list() {
|
||||||
// `chest:` is a list of 3–5 item strings.
|
// `chest:` is a list of 3–5 item strings.
|
||||||
let v = parse(&gen_level(3, 4).target_yaml);
|
let v = parse(&checked_level(3, 4).target_yaml);
|
||||||
let chest = field(&v, "chest").as_sequence().expect("chest is a list");
|
let chest = field(&v, "chest").as_sequence().expect("chest is a list");
|
||||||
assert!((3..=5).contains(&chest.len()), "chest holds 3–5 items");
|
assert!((3..=5).contains(&chest.len()), "chest holds 3–5 items");
|
||||||
assert!(chest.iter().all(Value::is_string), "every item is a string");
|
assert!(chest.iter().all(Value::is_string), "every item is a string");
|
||||||
@@ -187,7 +201,7 @@ mod smoke {
|
|||||||
#[test]
|
#[test]
|
||||||
fn level_05_chambers_is_a_dict_of_lists() {
|
fn level_05_chambers_is_a_dict_of_lists() {
|
||||||
// `chambers:` is a dict of 2–3 lists, 2–3 items each.
|
// `chambers:` is a dict of 2–3 lists, 2–3 items each.
|
||||||
let v = parse(&gen_level(4, 5).target_yaml);
|
let v = parse(&checked_level(4, 5).target_yaml);
|
||||||
let chambers = field(&v, "chambers")
|
let chambers = field(&v, "chambers")
|
||||||
.as_mapping()
|
.as_mapping()
|
||||||
.expect("chambers is a dict");
|
.expect("chambers is a dict");
|
||||||
@@ -202,7 +216,7 @@ mod smoke {
|
|||||||
fn level_06_trap_repeats_in_every_room() {
|
fn level_06_trap_repeats_in_every_room() {
|
||||||
// `trap:` is defined once; every room repeats it verbatim, so a
|
// `trap:` is defined once; every room repeats it verbatim, so a
|
||||||
// player using `&anchor`/`*alias` parses to the same Value.
|
// player using `&anchor`/`*alias` parses to the same Value.
|
||||||
let v = parse(&gen_level(5, 6).target_yaml);
|
let v = parse(&checked_level(5, 6).target_yaml);
|
||||||
let trap = field(&v, "trap");
|
let trap = field(&v, "trap");
|
||||||
for key in ["type", "depth", "spikes"] {
|
for key in ["type", "depth", "spikes"] {
|
||||||
assert!(trap.get(key).is_some(), "trap carries `{key}`");
|
assert!(trap.get(key).is_some(), "trap carries `{key}`");
|
||||||
@@ -217,7 +231,7 @@ mod smoke {
|
|||||||
#[test]
|
#[test]
|
||||||
fn level_07_floor_map_nests_maps_and_lists() {
|
fn level_07_floor_map_nests_maps_and_lists() {
|
||||||
// `floor:` int + `rooms:` dict; each room nests two lists.
|
// `floor:` int + `rooms:` dict; each room nests two lists.
|
||||||
let v = parse(&gen_level(6, 7).target_yaml);
|
let v = parse(&checked_level(6, 7).target_yaml);
|
||||||
assert!(field(&v, "floor").is_i64(), "floor is an integer");
|
assert!(field(&v, "floor").is_i64(), "floor is an integer");
|
||||||
let rooms = field(&v, "rooms").as_mapping().expect("rooms is a dict");
|
let rooms = field(&v, "rooms").as_mapping().expect("rooms is a dict");
|
||||||
assert!(!rooms.is_empty(), "at least one room");
|
assert!(!rooms.is_empty(), "at least one room");
|
||||||
@@ -236,7 +250,7 @@ mod smoke {
|
|||||||
fn level_08_scroll_keeps_explicit_types() {
|
fn level_08_scroll_keeps_explicit_types() {
|
||||||
// Explicit types: a multi-line string, a float, and a digit-only
|
// Explicit types: a multi-line string, a float, and a digit-only
|
||||||
// string that must NOT collapse to an integer.
|
// string that must NOT collapse to an integer.
|
||||||
let v = parse(&gen_level(7, 8).target_yaml);
|
let v = parse(&checked_level(7, 8).target_yaml);
|
||||||
let scroll = field(&v, "scroll").as_str().expect("scroll is a string");
|
let scroll = field(&v, "scroll").as_str().expect("scroll is a string");
|
||||||
assert!(scroll.contains('\n'), "scroll preserves its newlines");
|
assert!(scroll.contains('\n'), "scroll preserves its newlines");
|
||||||
assert!(field(&v, "weight").is_f64(), "weight is a float");
|
assert!(field(&v, "weight").is_f64(), "weight is a float");
|
||||||
@@ -252,7 +266,7 @@ mod smoke {
|
|||||||
fn level_09_doors_merge_shared_defaults() {
|
fn level_09_doors_merge_shared_defaults() {
|
||||||
// Merge keys: each door carries a literal `<<` whose value is the
|
// Merge keys: each door carries a literal `<<` whose value is the
|
||||||
// shared defaults dict, plus its own override.
|
// shared defaults dict, plus its own override.
|
||||||
let v = parse(&gen_level(8, 9).target_yaml);
|
let v = parse(&checked_level(8, 9).target_yaml);
|
||||||
let defaults = field(&v, "door_defaults");
|
let defaults = field(&v, "door_defaults");
|
||||||
for door in ["north_door", "south_door"] {
|
for door in ["north_door", "south_door"] {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -269,7 +283,7 @@ mod smoke {
|
|||||||
fn level_10_ledger_forgives_numeric_forms() {
|
fn level_10_ledger_forgives_numeric_forms() {
|
||||||
// The ledger: int gold/silver, float experience, ISO date. The
|
// The ledger: int gold/silver, float experience, ISO date. The
|
||||||
// lesson is numeric forgiveness, so hex must score a perfect match.
|
// lesson is numeric forgiveness, so hex must score a perfect match.
|
||||||
let g = gen_level(9, 10);
|
let g = checked_level(9, 10);
|
||||||
let v = parse(&g.target_yaml);
|
let v = parse(&g.target_yaml);
|
||||||
let vault = field(&v, "vault");
|
let vault = field(&v, "vault");
|
||||||
let gold = field(vault, "gold").as_i64().expect("gold is an integer");
|
let gold = field(vault, "gold").as_i64().expect("gold is an integer");
|
||||||
@@ -291,7 +305,7 @@ mod smoke {
|
|||||||
fn level_11_copies_alias_defined_shapes() {
|
fn level_11_copies_alias_defined_shapes() {
|
||||||
// `shapes:` defines polygons; `copies:` reuses them, so each copy
|
// `shapes:` defines polygons; `copies:` reuses them, so each copy
|
||||||
// is structurally identical to one of the definitions.
|
// is structurally identical to one of the definitions.
|
||||||
let v = parse(&gen_level(10, 11).target_yaml);
|
let v = parse(&checked_level(10, 11).target_yaml);
|
||||||
let shapes = field(&v, "shapes").as_sequence().expect("shapes is a list");
|
let shapes = field(&v, "shapes").as_sequence().expect("shapes is a list");
|
||||||
assert!((2..=3).contains(&shapes.len()), "2–3 defined shapes");
|
assert!((2..=3).contains(&shapes.len()), "2–3 defined shapes");
|
||||||
for s in shapes {
|
for s in shapes {
|
||||||
|
|||||||
73
src/tui.rs
73
src/tui.rs
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user