elvish_config/lib/moi/util/strutil.elv

116 lines
2.0 KiB
Plaintext

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