lumesh 0.18.2

a lighting shell ⚡ bash alternative
Documentation
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use crate::{Environment, Expression};
use std::collections::BTreeMap;
use std::fs::OpenOptions;

use crate::libs::BuiltinInfo;
use crate::libs::helper::{check_args_len, check_exact_args_len, get_string_ref};
use crate::libs::lazy_module::LazyModule;
use crate::{Int, RuntimeError, reg_info, reg_lazy};

use crossterm::cursor::{
    Hide, MoveDown, MoveLeft, MoveRight, MoveTo, MoveUp, RestorePosition, SavePosition, Show,
};
use crossterm::event::{Event, KeyCode, read};
use crossterm::style::Print;
use crossterm::terminal::{
    Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, SetTitle, disable_raw_mode,
    enable_raw_mode, size,
};
use crossterm::{execute, queue};
use std::io::{Write, stdout};

pub fn regist_lazy() -> LazyModule {
    reg_lazy!({
        // Console information
        width, height,
        // Output control
        write, title, clear, flush, bell,
        // Mode control
        raw_mode, alt_screen, line_wrap,
        // Cursor control
        cursor_to, cursor_up, cursor_down, cursor_left, cursor_right, cursor_save, cursor_restore, cursor_hide, cursor_show,
        // Input control
        read_line, read_password, read_key,
        keys,
        // Output control
        print_tty, discard
    })
}

pub fn regist_info() -> BTreeMap<&'static str, BuiltinInfo> {
    reg_info!({
        // Console information
        width => "console width", ""
        height => "console height", ""

        // Output control
        write => "write text at position", "<text> <x> <y>"
        title => "set console title", "<string>"
        clear => "clear console", ""
        flush => "flush stdout", ""
        bell => "ring terminal bell", ""

        // Mode control
        raw_mode => "get/set raw mode", "[bool]"
        alt_screen => "enter/leave alternate screen", "<bool>"
        line_wrap => "enable/disable line wrap", "<bool>"

        // Cursor control
        cursor_to => "move cursor to position", "<x> <y>"
        cursor_up => "move cursor up n rows", "<n>"
        cursor_down => "move cursor down n rows", "<n>"
        cursor_left => "move cursor left n cols", "<n>"
        cursor_right => "move cursor right n cols", "<n>"
        cursor_save => "save cursor position", ""
        cursor_restore => "restore cursor position", ""
        cursor_hide => "hide cursor", ""
        cursor_show => "show cursor", ""

        // Input control
        read_line => "read line from stdin", "[prompt]"
        read_password => "read password, masked", "[prompt]"
        read_key => "read one key, enters raw mode temporarily. e.g. 'enter','f1','a'", ""
        keys => "list special key names", ""

        // Output control
        print_tty => "write raw text directly to tty, bypass pipes", "<text>"
        discard => "no-op, discards args", "<args>..."
    })
}

// Console Information Functions
fn width(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    size()
        .map(|(w, _)| Expression::Integer(w as Int))
        .or(Ok(Expression::None))
}

fn height(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    size()
        .map(|(_, h)| Expression::Integer(h as Int))
        .or(Ok(Expression::None))
}
// Text Output Functions
fn write(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("write", &args, 3, ctx)?;

    let x = &args[1];
    let y = &args[2];

    match (x, y) {
        (Expression::Integer(x), Expression::Integer(y)) => {
            let content_str = args[0].to_string();
            let mut out = stdout();
            for (y_offset, line) in content_str.lines().enumerate() {
                queue!(
                    out,
                    SavePosition,
                    MoveTo(*x as u16, (*y + y_offset as Int) as u16),
                    Print(line),
                    RestorePosition,
                )
                .map_err(|e| {
                    RuntimeError::common(format!("Write failed: {e}").into(), ctx.clone(), 0)
                })?;
            }
            out.flush().map_err(|e| {
                RuntimeError::common(format!("Flush failed: {e}").into(), ctx.clone(), 0)
            })?;
            Ok(Expression::None)
        }
        (m, n) => Err(RuntimeError::common(
            format!(
                "Expected integers for position, got ({} {:?}, {} {:?})",
                m.type_name(),
                m,
                n.type_name(),
                n
            )
            .into(),
            ctx.clone(),
            0,
        )),
    }
}

fn title(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("title", &args, 1, ctx)?;
    execute!(stdout(), SetTitle(args[0].to_string())).map_err(|e| {
        RuntimeError::common(format!("Failed to set title: {e}").into(), ctx.clone(), 0)
    })?;
    Ok(Expression::None)
}

fn clear(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    execute!(stdout(), Clear(ClearType::All), MoveTo(0, 0))
        .map_err(|_| RuntimeError::common("Clear failed".into(), _ctx.clone(), 0))?;
    Ok(Expression::None)
}

fn flush(
    _args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    stdout()
        .flush()
        .map_err(|e| RuntimeError::common(format!("Flush failed: {e}").into(), ctx.clone(), 0))?;
    Ok(Expression::None)
}
// Console Mode Functions
fn raw_mode(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    if args.is_empty() {
        let r = crossterm::terminal::is_raw_mode_enabled().map_err(|_| {
            RuntimeError::common(
                "Failed to detect whether raw mode is enabled".into(),
                ctx.clone(),
                0,
            )
        })?;
        return Ok(Expression::Boolean(r));
    } else {
        if args[0].is_truthy() {
            enable_raw_mode().map_err(|_| {
                RuntimeError::common("Failed to enable raw mode".into(), ctx.clone(), 0)
            })?;
        } else {
            disable_raw_mode().map_err(|_| {
                RuntimeError::common("Failed to disable raw mode".into(), ctx.clone(), 0)
            })?;
        }
        return Ok(Expression::None);
    }
}

fn alt_screen(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("alt_screen", &args, 1, ctx)?;

    if args[0].is_truthy() {
        execute!(stdout(), EnterAlternateScreen).map_err(|_| {
            RuntimeError::common("Failed to enter alternate screen".into(), ctx.clone(), 0)
        })?;
    } else {
        execute!(stdout(), LeaveAlternateScreen).map_err(|_| {
            RuntimeError::common("Failed to leave alternate screen".into(), ctx.clone(), 0)
        })?;
    }
    return Ok(Expression::None);
}

fn line_wrap(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("line_wrap", &args, 1, ctx)?;

    if args[0].is_truthy() {
        execute!(stdout(), crossterm::terminal::EnableLineWrap).map_err(|_| {
            RuntimeError::common("Failed to enable line wrap".into(), ctx.clone(), 0)
        })?;
    } else {
        execute!(stdout(), crossterm::terminal::DisableLineWrap).map_err(|_| {
            RuntimeError::common("Failed to disable line wrap".into(), ctx.clone(), 0)
        })?;
    }
    return Ok(Expression::None);
}

// Cursor Control Functions
fn cursor_to(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("cursor_to", &args, 2, ctx)?;

    match (&args[0], &args[1]) {
        (Expression::Integer(x), Expression::Integer(y)) => {
            execute!(stdout(), MoveTo(*x as u16, *y as u16)).map_err(|e| {
                RuntimeError::common(format!("Failed to move cursor: {e}").into(), ctx.clone(), 0)
            })?;
            Ok(Expression::None)
        }
        (m, n) => Err(RuntimeError::common(
            format!(
                "Expected integers for position, got ({} {:?}, {} {:?})",
                m.type_name(),
                m,
                n.type_name(),
                n
            )
            .into(),
            ctx.clone(),
            0,
        )),
    }
}

fn cursor_up(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("cursor_up", &args, 1, ctx)?;
    if let Expression::Integer(n) = args[0] {
        execute!(stdout(), MoveUp(n as u16)).map_err(|e| {
            RuntimeError::common(format!("Failed to move cursor: {e}").into(), ctx.clone(), 0)
        })?;
        Ok(Expression::None)
    } else {
        Err(RuntimeError::common(
            format!("Expected integer for movement amount, got {:?}", args[0]).into(),
            ctx.clone(),
            0,
        ))
    }
}

fn cursor_down(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("cursor_down", &args, 1, ctx)?;
    if let Expression::Integer(n) = args[0] {
        execute!(stdout(), MoveDown(n as u16)).map_err(|e| {
            RuntimeError::common(format!("Failed to move cursor: {e}").into(), ctx.clone(), 0)
        })?;
        Ok(Expression::None)
    } else {
        Err(RuntimeError::common(
            format!("Expected integer for movement amount, got {:?}", args[0]).into(),
            ctx.clone(),
            0,
        ))
    }
}

fn cursor_left(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("cursor_left", &args, 1, ctx)?;
    if let Expression::Integer(n) = args[0] {
        execute!(stdout(), MoveLeft(n as u16)).map_err(|e| {
            RuntimeError::common(format!("Failed to move cursor: {e}").into(), ctx.clone(), 0)
        })?;
        Ok(Expression::None)
    } else {
        Err(RuntimeError::common(
            format!("Expected integer for movement amount, got {:?}", args[0]).into(),
            ctx.clone(),
            0,
        ))
    }
}

fn cursor_right(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("cursor_right", &args, 1, ctx)?;
    if let Expression::Integer(n) = args[0] {
        execute!(stdout(), MoveRight(n as u16)).map_err(|e| {
            RuntimeError::common(format!("Failed to move cursor: {e}").into(), ctx.clone(), 0)
        })?;
        Ok(Expression::None)
    } else {
        Err(RuntimeError::common(
            format!("Expected integer for movement amount, got {:?}", args[0]).into(),
            ctx.clone(),
            0,
        ))
    }
}

fn cursor_save(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    execute!(stdout(), SavePosition).map_err(|_| {
        RuntimeError::common("Failed to save cursor position".into(), _ctx.clone(), 0)
    })?;
    Ok(Expression::None)
}

fn cursor_restore(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    execute!(stdout(), RestorePosition).map_err(|_| {
        RuntimeError::common("Failed to restore cursor position".into(), _ctx.clone(), 0)
    })?;
    Ok(Expression::None)
}

fn cursor_hide(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    execute!(stdout(), Hide)
        .map_err(|_| RuntimeError::common("Failed to hide cursor".into(), _ctx.clone(), 0))?;
    Ok(Expression::None)
}

fn cursor_show(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    execute!(stdout(), Show)
        .map_err(|_| RuntimeError::common("Failed to show cursor".into(), _ctx.clone(), 0))?;
    Ok(Expression::None)
}

// Key mapping constants shared between read_key and keys
const SPECIAL_KEY_MAPPINGS: &[(&str, KeyCode)] = &[
    ("space", KeyCode::Char(' ')),
    ("enter", KeyCode::Enter),
    ("backspace", KeyCode::Backspace),
    ("delete", KeyCode::Delete),
    ("left", KeyCode::Left),
    ("right", KeyCode::Right),
    ("up", KeyCode::Up),
    ("down", KeyCode::Down),
    ("home", KeyCode::Home),
    ("end", KeyCode::End),
    ("page_up", KeyCode::PageUp),
    ("page_down", KeyCode::PageDown),
    ("tab", KeyCode::Tab),
    ("esc", KeyCode::Esc),
    ("insert", KeyCode::Insert),
    ("f1", KeyCode::F(1)),
    ("f2", KeyCode::F(2)),
    ("f3", KeyCode::F(3)),
    ("f4", KeyCode::F(4)),
    ("f5", KeyCode::F(5)),
    ("f6", KeyCode::F(6)),
    ("f7", KeyCode::F(7)),
    ("f8", KeyCode::F(8)),
    ("f9", KeyCode::F(9)),
    ("f10", KeyCode::F(10)),
    ("f11", KeyCode::F(11)),
    ("f12", KeyCode::F(12)),
    ("null", KeyCode::Null),
    ("back_tab", KeyCode::BackTab),
];

fn key_code_name(code: KeyCode) -> Option<&'static str> {
    SPECIAL_KEY_MAPPINGS
        .iter()
        .find(|(_, k)| *k == code)
        .map(|(name, _)| *name)
}

fn keys(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    Ok(Expression::from(
        SPECIAL_KEY_MAPPINGS
            .iter()
            .map(|(name, _)| Expression::String(name.to_string()))
            .collect::<Vec<_>>(),
    ))
}

// Input Functions
fn read_line(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    if let Some(prompt) = args.get(0) {
        println!("{}", prompt.to_string())
    }
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).map_err(|e| {
        RuntimeError::common(format!("Failed to read line: {e}").into(), ctx.clone(), 0)
    })?;
    Ok(Expression::String(input.trim_end_matches("\n").to_string()))
}

fn read_password(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_args_len("read_password", &args, 0..=1, ctx)?;
    let rst = if !args.is_empty() {
        rpassword::prompt_password(args[0].to_string())
    } else {
        rpassword::prompt_password("")
    };
    let r = rst.map_err(|e| {
        RuntimeError::common(
            format!("Failed to read password: {e}").into(),
            ctx.clone(),
            0,
        )
    })?;
    Ok(Expression::String(r))
}

fn read_key(
    _args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    enable_raw_mode()
        .map_err(|_| RuntimeError::common("Failed to enable raw mode".into(), ctx.clone(), 0))?;

    let result = loop {
        match read() {
            Ok(Event::Key(event)) => {
                let key_str = key_code_name(event.code)
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| match event.code {
                        KeyCode::Char(c) => c.to_string(),
                        _ => format!("{:?}", event.code),
                    });
                break Ok(Expression::String(key_str));
            }
            Ok(_) => continue, // 忽略鼠标、resize 等非 Key 事件,继续等待
            Err(e) => {
                break Err(RuntimeError::common(
                    format!("Failed to read key: {e}").into(),
                    ctx.clone(),
                    0,
                ));
            }
        }
    };

    disable_raw_mode()
        .map_err(|_| RuntimeError::common("Failed to disable raw mode".into(), ctx.clone(), 0))?;

    result
}

fn print_tty(
    args: Vec<Expression>,
    _env: &mut Environment,
    ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    check_exact_args_len("print_tty", &args, 1, ctx)?;

    // 判断操作系统
    let tty_path = if cfg!(windows) {
        "CON" // Windows控制台
    } else {
        "/dev/tty" // Unix
    };

    let mut tty = OpenOptions::new()
        .write(true)
        .open(tty_path)
        .map_err(|e| RuntimeError::from_io_error(e, "open tty".into(), Expression::None, 0))?;
    let v = get_string_ref(&args[0], ctx)?;
    tty.write_all(v.as_bytes())
        .map_err(|e| RuntimeError::from_io_error(e, "write tty".into(), Expression::None, 0))?;

    Ok(Expression::None)
}

fn bell(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    print!("\x07");
    Ok(Expression::None)
}

fn discard(
    _args: Vec<Expression>,
    _env: &mut Environment,
    _ctx: &Expression,
) -> Result<Expression, RuntimeError> {
    // 不用打开任何设备,只是丢弃参数
    Ok(Expression::None)
}