elvish_config/lib/moi/util/strutil.elv

115 lines
2.1 KiB
Plaintext
Raw Normal View History

use str
use ./list
2021-12-11 21:09:02 +00:00
fn -repeat {|n s|
repeat $n $s | str:join ''
}
2021-12-11 21:09:02 +00:00
fn left {|size s|
2021-08-27 20:06:49 +00:00
var ss = (count $s)
var d = (- $size $ss)
if (<= $d 0) {
put $s[:$size]
} else {
put $s(-repeat $d ' ')
}
}
2021-12-11 21:09:02 +00:00
fn right {|size s|
2021-08-27 20:06:49 +00:00
var ss = (count $s)
var d = (- $size $ss)
if (<= $d 0) {
put $s[:$size]
} else {
put (-repeat $d ' ')$s
}
}
2021-12-11 21:09:02 +00:00
fn center {|size s|
use math
2021-08-27 20:06:49 +00:00
var ss = (count $s)
var d = (- $size $ss)
if (<= $d 0) {
2021-08-27 20:06:49 +00:00
var l = (math:ceil (/ -$d 2))
var r = (- (+ $ss $d) $l)
put $s[$l':'$r]
} else {
2021-08-27 20:06:49 +00:00
var l = (math:ceil (/ $d 2))
var r = (- $d $l)
put (-repeat $l ' ')$s(-repeat $r ' ')
}
}
2021-12-11 21:09:02 +00:00
fn -c2map {|col|
if (not-eq (kind-of $col) list) {
put []
return
}
2021-12-11 21:09:02 +00:00
list:loop {|i c|
2021-08-27 20:06:49 +00:00
var k = (kind-of $c)
var cf = [&min=0]
if (is $k string) {
2021-10-13 18:49:48 +00:00
set cf[min] = $c
} elif (is $k map) {
if (has-key $c min) {
2021-10-13 18:49:48 +00:00
set cf[min] = $c[min]
}
if (has-key $c align) {
2021-10-13 18:49:48 +00:00
set cf[align] = $c[align]
}
}
2021-10-13 18:49:48 +00:00
set col[$i] = $cf
} $col
put $col
}
2021-12-11 21:09:02 +00:00
fn -parsecols {|col &split=$false lst|
2021-10-13 18:49:48 +00:00
set col = (-c2map $col)
2021-08-27 20:06:49 +00:00
var cc lines = (count $col) $lst
if $split {
2021-12-11 21:09:02 +00:00
set lines = [ (eawk {|_ @args| put $args } $lst) ]
}
2021-12-11 21:09:02 +00:00
each {|l|
2021-08-27 20:06:49 +00:00
var cl = (count $l)
if (> $cl $cc) {
2021-12-11 21:09:02 +00:00
set col = [ $@col (range (- $cl $cc) | each {|_| put [&align=left &min=0] }) ]
2021-10-13 18:49:48 +00:00
set cc = $cl
}
2021-12-11 21:09:02 +00:00
list:loop {|i c|
2021-08-27 20:06:49 +00:00
var ccl = (+ (count $c) 1)
if (> $ccl $col[$i][min]) {
2021-10-13 18:49:48 +00:00
set col[$i][min] = $ccl
}
} $l
} $lines
put $col
}
2021-12-11 21:09:02 +00:00
fn -format {|f e|
2021-08-27 20:06:49 +00:00
var cb = $left~
if (has-key $f align) {
2021-08-27 20:06:49 +00:00
var a = $f[align]
if (is $a right) {
2021-10-13 18:49:48 +00:00
set cb = $right~
} elif (is $a center) {
2021-10-13 18:49:48 +00:00
set cb = $center~
}
}
$cb $f[min] $e
}
2021-12-11 21:09:02 +00:00
fn -formatline {|col line|
list:loop {|i v|
-format $col[$i] $v
} $line | str:join ''
}
2021-12-11 21:09:02 +00:00
fn format {|&col=[] &split=$false @lst|
2021-08-27 20:06:49 +00:00
var lines = (list:-p $@lst)
if $split {
2021-12-11 21:09:02 +00:00
set lines = [ (eawk {|l @args| put $args } $lines) ]
}
2021-10-13 18:49:48 +00:00
set col = (-parsecols $col $lines)
2021-12-11 21:09:02 +00:00
each {|l| -formatline $col $l } $lines
}