Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sk33p"
version = "0.2.0"
version = "0.3.0"
edition = "2021"
rust-version = "1.75"
license = "MIT"
Expand Down
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ sk33p get budget.xlsx C4
sk33p set budget.xlsx B2 5 C2 '=B2*2' # writes and saves
sk33p cat budget.xlsx A1:C10 --csv
sk33p convert budget.xlsx budget.csv
sk33p sort budget.xlsx A1:D10 --by C --desc --header -o sorted.xlsx
sk33p cat budget.xlsx --where "C>100" --csv # rows matching a filter
sk33p ask "sum of D2:D6 plus 8% tax" budget.xlsx --cell D12 # a formula from c0mpute
sk33p mcp # Model Context Protocol server on stdio
```
Expand All @@ -37,6 +39,32 @@ TUI keys: arrows or hjkl move, type or `=` to enter, Enter/F2 edit, Tab commit
right, Del clear, Ctrl+Z / Ctrl+Y undo and redo, `[` `]` switch sheet, `<` `>`
column width, `g` go to, `:w file.xlsx` save as, `:q` quit, `?` all keys.

## Mouse, selection, sort and filter

- **Select:** click a cell, drag for a range, Shift+click to extend,
Ctrl+click or Alt+click to add another range. Click a column letter or row
number for the whole column or row (drag or Ctrl+click for several), the
corner or Ctrl+A for everything. Shift+arrows extend from the keyboard, Esc
collapses. Double-click edits a cell; the wheel scrolls rows, Shift+wheel
columns.
- The name box shows the selection (`B2:C6, D:D`) and the status bar shows
`Sum= Avg= Count=` for its numbers.
- **Clipboard:** Del clears the selection, Ctrl+C copies it as TSV (to the
system clipboard over OSC 52), Ctrl+V pastes at the cursor and shifts
formulas the way Excel does. Each is one undo step.
- **Sort:** `s` / `S` sorts the selection (or the data region) by the cursor's
column, ascending / descending, keeping a header row. `:sort B desc, C asc`
sorts by several keys. Numbers sort as numbers, text ignores case, blanks go
last. A formula that points at another row with a relative reference stops
the sort, with the cell named, instead of breaking the formula.
- **Filter:** `f` turns on a filter (▾ on the header row; click one for a
prompt). `:filter C > 100`, `:filter A contains widget`, `:filter C off`,
`:filter off`. Filters hide rows on screen only; they never change the data.

macOS terminals keep Cmd+click for themselves (it opens links), so use Ctrl+click
or Alt+click to add ranges. Most terminals also keep Shift+click for their own
text selection; plain xterm opens a menu on Ctrl+click, so use Alt+click there.

## Ask

Ask for a formula in plain language; models on the [c0mpute](https://c0mpute.com)
Expand Down
80 changes: 73 additions & 7 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Non-interactive subcommands. Each prints to stdout and exits non-zero on error.
use crate::engine::{cell_name, parse_range, parse_ref, Engine, Kind};
use crate::table;
use std::path::Path;

pub const USAGE: &str = "\
Expand All @@ -11,8 +12,13 @@ USAGE
sk33p get FILE REF [-s SHEET] print a cell's value (add --formula for its input)
sk33p set FILE REF VALUE... [-s SHEET] [-o OUT]
write cells (REF VALUE pairs) and save (to OUT or FILE; created if missing)
sk33p cat FILE [RANGE] [-s SHEET] [--csv|--tsv]
print a sheet or range as a grid, CSV or TSV
sk33p cat FILE [RANGE] [-s SHEET] [--csv|--tsv] [--where \"C>100\"]...
print a sheet or range as a grid, CSV or TSV; --where keeps
matching rows (ops = != > >= < <= contains; repeat to AND)
and the header row (detected, or --header / --no-header)
sk33p sort FILE [RANGE] [--by C|--by \"B desc, C asc\"] [--desc] [--header|--no-header] [-s SHEET] [-o OUT]
sort the rows of RANGE (default: the used range) and save;
numbers numerically, text case-insensitively, blanks last
sk33p sheets FILE list sheet names
sk33p convert IN OUT [-s SHEET] convert between .xlsx .sker .csv .tsv
sk33p demo [OUT] write a sample workbook (default sk33p-demo.xlsx)
Expand All @@ -24,6 +30,11 @@ USAGE

TUI KEYS
arrows/hjkl move Enter/F2 edit type or = to start Del clear Ctrl+Z/Ctrl+Y undo/redo
mouse: click a cell, drag a range, Ctrl/Alt+click adds a range, click A B C / 1 2 3 for whole
columns/rows, wheel scrolls (Shift+wheel sideways), double-click edits
(macOS terminals keep Cmd for themselves: use Ctrl or Alt+click to add ranges)
Shift+arrows extend Ctrl+A select all Ctrl+C/Ctrl+V copy/paste (TSV, OSC 52 clipboard)
s/S sort asc/desc by the cursor column (:sort B desc, C) f AutoFilter (:filter C > 100, :filter off)
Ctrl+S save : command (:w :q :e FILE :goto B12 :sheet NAME :addsheet :delsheet :ir :dr :ic :dc)
[ ] prev/next sheet < > column width g goto ? help Ctrl+Q quit
Ctrl+K or [Ask] or a cell typed as ?QUESTION: ask c0mpute for a formula; Enter accepts, Esc drops
Expand All @@ -33,16 +44,20 @@ struct Args {
pos: Vec<String>,
sheet: Option<String>,
out: Option<String>,
by: Option<String>,
wheres: Vec<String>,
flags: Vec<String>,
}

fn parse(args: &[String]) -> Result<Args, String> {
let mut a = Args { pos: vec![], sheet: None, out: None, flags: vec![] };
let mut a = Args { pos: vec![], sheet: None, out: None, by: None, wheres: vec![], flags: vec![] };
let mut it = args.iter();
while let Some(x) = it.next() {
match x.as_str() {
"-s" | "--sheet" => a.sheet = Some(it.next().ok_or("--sheet needs a name")?.clone()),
"-o" | "--out" => a.out = Some(it.next().ok_or("--out needs a path")?.clone()),
"--by" => a.by = Some(it.next().ok_or("--by needs a column, e.g. --by C")?.clone()),
"--where" | "-w" => a.wheres.push(it.next().ok_or("--where needs a condition, e.g. --where \"C>100\"")?.clone()),
f if f.starts_with("--") => a.flags.push(f.to_string()),
_ => a.pos.push(x.clone()),
}
Expand Down Expand Up @@ -115,6 +130,41 @@ pub fn run(cmd: &str, rest: &[String]) -> Result<(), String> {
Some(r) => parse_range(r).ok_or(format!("bad range {r:?}"))?,
None => ((1, 1), (e.last_row().max(1), e.last_col().max(1))),
};
if a.wheres.is_empty() {
print!("{}", render(&e, (r0, c0), (r1, c1), &a.flags));
} else {
let conds = a.wheres.iter().map(|w| table::parse_cond(w)).collect::<Result<Vec<_>, _>>()?;
let rows = table::filter_range(&e, (r0, c0, r1, c1), &conds, header_flag(&a.flags));
print!("{}", render_rows(&e, &rows, c0, c1, &a.flags));
}
Ok(())
}
"sort" => {
let file = a.pos.first().ok_or("usage: sk33p sort FILE [RANGE] [--by C] [--desc] [-o OUT]")?;
let mut e = open(file, &a.sheet)?;
let ((r0, c0), (r1, c1)) = match a.pos.get(1) {
Some(r) => parse_range(r).ok_or(format!("bad range {r:?}"))?,
None => ((1, 1), (e.last_row().max(1), e.last_col().max(1))),
};
let desc = a.flags.iter().any(|f| f == "--desc");
let by = a.by.clone().unwrap_or_default();
let spec = if desc && !by.contains(',') && !by.to_ascii_lowercase().split_whitespace().any(|w| w.starts_with("asc") || w.starts_with("desc")) {
format!("{by} desc")
} else {
by
};
let (keys, _) = table::parse_sort_spec(&spec, c0)?;
let done = table::sort_range(&mut e, (r0, c0, r1, c1), &keys, header_flag(&a.flags))?;
let out = a.out.clone().unwrap_or_else(|| file.clone());
e.save(Path::new(&out))?;
let by: Vec<String> = keys.iter().map(|k| format!("{} {}", crate::engine::col_name(k.col), if k.desc { "desc" } else { "asc" })).collect();
eprintln!(
"sorted {}:{} by {}{}; wrote {out}",
cell_name(done.rect.0, c0),
cell_name(r1, c1),
by.join(", "),
if done.header { format!(" (header row {r0} kept)") } else { String::new() }
);
print!("{}", render(&e, (r0, c0), (r1, c1), &a.flags));
Ok(())
}
Expand All @@ -137,8 +187,24 @@ pub fn run(cmd: &str, rest: &[String]) -> Result<(), String> {
}
}

fn header_flag(flags: &[String]) -> Option<bool> {
if flags.iter().any(|f| f == "--header") {
Some(true)
} else if flags.iter().any(|f| f == "--no-header") {
Some(false)
} else {
None
}
}

/// A plain-text grid, or CSV/TSV with --csv / --tsv.
pub fn render(e: &Engine, (r0, c0): (usize, usize), (r1, c1): (usize, usize), flags: &[String]) -> String {
let rows: Vec<usize> = (r0..=r1).collect();
render_rows(e, &rows, c0, c1, flags)
}

/// `render` for a chosen set of rows (a filtered range keeps its row numbers).
pub fn render_rows(e: &Engine, rows: &[usize], c0: usize, c1: usize, flags: &[String]) -> String {
let sep = if flags.iter().any(|f| f == "--csv") {
Some(',')
} else if flags.iter().any(|f| f == "--tsv") {
Expand All @@ -148,7 +214,7 @@ pub fn render(e: &Engine, (r0, c0): (usize, usize), (r1, c1): (usize, usize), fl
};
let mut out = String::new();
if let Some(sep) = sep {
for r in r0..=r1 {
for &r in rows {
let cells: Vec<String> = (c0..=c1)
.map(|c| {
let v = e.display(r, c);
Expand All @@ -161,21 +227,21 @@ pub fn render(e: &Engine, (r0, c0): (usize, usize), (r1, c1): (usize, usize), fl
return out;
}
let grid: Vec<Vec<(String, Kind)>> =
(r0..=r1).map(|r| (c0..=c1).map(|c| (e.display(r, c), e.kind(r, c))).collect()).collect();
rows.iter().map(|&r| (c0..=c1).map(|c| (e.display(r, c), e.kind(r, c))).collect()).collect();
let widths: Vec<usize> = (0..=(c1 - c0))
.map(|i| {
let head = crate::engine::col_name(c0 + i).len();
grid.iter().map(|row| row[i].0.chars().count()).max().unwrap_or(0).max(head).min(40)
})
.collect();
let rw = r1.to_string().len();
let rw = rows.iter().max().copied().unwrap_or(1).to_string().len();
out.push_str(&" ".repeat(rw));
for (i, w) in widths.iter().enumerate() {
out.push_str(&format!(" | {:^w$}", crate::engine::col_name(c0 + i), w = w));
}
out.push('\n');
for (ri, row) in grid.iter().enumerate() {
out.push_str(&format!("{:>rw$}", r0 + ri, rw = rw));
out.push_str(&format!("{:>rw$}", rows[ri], rw = rw));
for (i, (v, k)) in row.iter().enumerate() {
let v: String = v.chars().take(widths[i]).collect();
if matches!(k, Kind::Number) {
Expand Down
66 changes: 65 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ mod cli;
mod demo;
mod engine;
mod mcp;
mod select;
mod table;
mod tui;

fn main() {
Expand All @@ -28,7 +30,7 @@ fn main() {
println!("wrote {out}: open it with `sk33p {out}`");
Ok(())
})(),
Some(cmd @ ("eval" | "get" | "set" | "cat" | "sheets" | "convert")) => cli::run(cmd, &args[1..]),
Some(cmd @ ("eval" | "get" | "set" | "cat" | "sort" | "sheets" | "convert")) => cli::run(cmd, &args[1..]),
Some(path) if !path.starts_with('-') => tui::run(Some(path.into())),
Some(other) => Err(format!("unknown option {other:?}\n\n{}", cli::USAGE)),
None => tui::run(None),
Expand Down Expand Up @@ -119,6 +121,68 @@ mod tests {
let text = r["result"]["content"][0]["text"].as_str().unwrap().to_string();
assert!(text.contains("1024") && text.contains("=POWER(A1,10)"), "{text}");

// Mouse selection, sort, filter and the clipboard in the TUI.
{
let e = Engine::new().unwrap();
let _e = crate::tui::mouse_flow_for_test(e);
}

// Sort and filter without the TUI: CLI `sort` / `cat --where`, MCP `sort_range` / `read_range` `where`.
{
let book = dir.join("s.sker");
{
let mut e = Engine::new().unwrap();
for (r, row) in [["name", "score"], ["bo", "7"], ["Al", ""], ["cy", "10"], ["al", "2"]].iter().enumerate() {
for (c, v) in row.iter().enumerate() {
e.set(r + 1, c + 1, v).unwrap();
}
}
e.save(&book).unwrap();
}
let args = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let out = dir.join("s2.sker");
crate::cli::run("sort", &args(&[book.to_str().unwrap(), "A1:B5", "--by", "B", "--desc", "-o", out.to_str().unwrap()])).unwrap();
{
let e = Engine::new().unwrap();
let mut e = e;
e.load(&out).unwrap();
let col: Vec<String> = (1..=5).map(|r| e.display(r, 1)).collect();
assert_eq!(col, ["name", "cy", "bo", "al", "Al"], "header kept, numbers desc, blank last");
e.load(&book).unwrap();
assert_eq!(e.display(2, 1), "bo", "-o leaves the input alone");
let rows = crate::table::filter_range(&e, (1, 1, 5, 2), &[crate::table::parse_cond("B>=7").unwrap()], None);
assert_eq!(rows, vec![1, 2, 4]);
let text = crate::cli::render_rows(&e, &rows, 1, 2, &[]);
assert!(text.contains("name") && text.contains("cy") && !text.contains("al"), "{text}");
assert!(text.lines().last().unwrap().trim_start().starts_with('4'), "filtered rows keep their numbers:\n{text}");
}
crate::cli::run("cat", &args(&[book.to_str().unwrap(), "A1:B5", "--where", "A contains l", "--csv"])).unwrap();
assert!(crate::cli::run("cat", &args(&[book.to_str().unwrap(), "--where", "B ~ 1"])).is_err());
// text sorts case-insensitively and stably: Al before al (input order)
crate::cli::run("sort", &args(&[book.to_str().unwrap(), "--by", "A"])).unwrap();
{
let mut e = Engine::new().unwrap();
e.load(&book).unwrap();
let col: Vec<String> = (1..=5).map(|r| e.display(r, 1)).collect();
assert_eq!(col, ["name", "Al", "al", "bo", "cy"]);
}
let r = crate::mcp::handle(&json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"sort_range","arguments":{"path": book, "by": "B desc"}}})).unwrap();
assert!(r["result"]["isError"].is_null(), "{r}");
let v = &r["result"]["structuredContent"]["result"];
assert_eq!(v["sorted"], "A2:B5");
assert_eq!(v["header"], true);
assert_eq!(v["values"][1], json!(["cy", "10"]));
let r = crate::mcp::handle(&json!({"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"read_range","arguments":{"path": book, "where": ["B > 1", "B < 10"]}}})).unwrap();
let v = &r["result"]["structuredContent"]["result"];
assert_eq!(v["rows"], json!([1, 3, 4]), "{v}");
assert_eq!(v["values"], json!([["name", "score"], ["bo", "7"], ["al", "2"]]));
// without where, read_range is unchanged (no `rows`)
let r = crate::mcp::handle(&json!({"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"read_range","arguments":{"path": book, "range": "A1:A2"}}})).unwrap();
assert!(r["result"]["structuredContent"]["result"].get("rows").is_none());
let r = crate::mcp::handle(&json!({"jsonrpc":"2.0","id":7,"method":"tools/list"})).unwrap();
assert!(r.to_string().contains("sort_range"));
}

// TUI Ask against a stand-in for the cloud endpoint.
{
let (url, seen) = fake_ask_server();
Expand Down
Loading
Loading