使用Lumesh编写lf配置文件的语法演示
lf 文件管理器是一个非常强大的TUI文件管理器,支持高度灵活的自定义操作。是我最喜欢的文件管理器。以下是用Lumesh为lf编写的命令配置的部分演示。
1. 变量定义和管道操作#
1cmd all-cmd ${{
2 let cmd = lf -remote `query $id cmds` | .lines() | .drop(1) | \
3 .map(x -> {x.split("\t\t", $x) | .first()}) | Ui.pick "select cmd:"
4 lf -remote `send $id :$cmd`
5}}lf -remotequery $id cmds``获取lf可用命令let变量定义- 管道操作符
|用于数据流处理 .lines()字符串处理方法.drop(1)列表操作,跳过第一个元素.map()函数式编程,使用lambda表达式x -> {...}Ui.pick交互式选择器
2. 字符串处理和表格操作#
1cmd history-dir ${{
2 let hist = lf -remote `query $id jumps` | Into.table('jump','path') | .drop(1) | Ui.pick "choose history:"
3 lf --remote `send $id cd ${$hist.path}`
4}}lf -remotequery $id jumps获取lf的历史目录Into.table()将数据转换为表格结构- 字符串插值
${$hist.path}语法 - 对象属性访问
$hist.path
3. 条件语句和模式匹配#
1cmd toggle-preview %{{
2 match $lf_preview {
3 true => lf -remote `send $id :set nopreview; set ratios 1:5`
4 _ => lf -remote `send $id :set preview; set ratios 1:2:3`
5 }
6}}Lumesh的match模式匹配语法,类似Rust的match表达式。
这里匹配的是true字符串,如需bool值应大写首字母True
4. 条件表达式和三元操作#
1cmd select-files &{{
2 let htag= $lf_hidden ? '-H' : ''
3 let r=fd --exact-depth 1 $argv $htag -c never -j 1 -0 | xargs -0 printf ' %q'
4 lf -remote `send $id :unselect; toggle $r`
5}}- 三元条件操作符
condition ? value1 : value2 - 变量在命令行中的使用:
$argv为函数接收到的参数
5. 函数式编程和列表操作#
1cmd yank-name &{{
2 $fx.lines() | .map(Fs.base_name) | .join("\n") | wl-copy
3}}- 方法链式调用
.lines().map().join() Fs.base_name文件系统模块函数- 管道操作将结果传递给外部命令
6. 用户交互#
1cmd delete ${{
2 println '=====DELETE=====' $fx '================'
3 if Ui.confirm('Delete these files [y/n]:'){
4 $lf_user_wheel rm -rf $fx.lines()
5 }
6}}println输出函数Ui.confirm确认对话框if条件语句
7. 复杂的数据处理和循环#
1cmd mpaste %{{
2 let load=Fs.read ~/.local/share/lf/files | .lines()
3 let files = $load.drop(1)
4 let file_count = len($files)
5 if $file_count==0 {
6 print 'No files yanked'
7 exit 0
8 }
9 let mode=$load.at(0)
10 let base_names = $files.map(Fs.base_name)
11 let ans = read `$mode $file_count files? [y/N]`
12 if $ans == 'y' {
13 match $mode {
14 copy => {
15 $lf_user_wheel cp -r $argv -- $files '.'
16 let tg='='
17 }
18 move => {
19 $lf_user_wheel mv -- $files '.'
20 let tg='>'
21 }
22 }
23 for file in $base_names {
24 lf -remote `send $id :select "$file"; tag $tg`
25 }
26 }
27}}Fs.read文件读取len()长度函数read用户输入函数for循环语句- 复杂的match模式匹配
8. 正则表达式和字符串操作#
1cmd extract-to %{{
2 let dest = $argv[0] ?: {print 'Cancelled'; exit 0}
3 if (Regex.match '\.([gb7xs]z|t[gbx]z|zip|zst|bz2|lz4|lzma|tar|rar|br)$' $f) {
4 $lf_user_wheel ouch -q decompress --dir $dest $f
5 let base_name = Fs.base_name($f)
6 lf -remote `send $id :cd $dest; select $base_name; tag '^'`
7 }else{
8 print 'Unsupported file extention'
9 }
10}}- 空值合并操作符
?: Regex.match正则表达式匹配- 块表达式
{print 'Cancelled'; exit 0}
Notes#
这个配置文件完美展示了Lumesh作为shell脚本语言的强大功能:结合了现代编程语言的语法特性(如模式匹配、函数式编程、错误处理)与传统shell的命令执行能力。Lumesh的设计理念"像Python/JS一样编写,像bash一样工作"在这个实例中得到了充分体现。
Wiki pages you might want to explore: