elvish_config/lib/moi/util/strutil.elv

115 lines
2.1 KiB
Plaintext
Raw Normal View History

use str
use ./list
fn -repeat [n s]{
repeat $n $s | str:join ''
}
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 ' ')
}
}
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
}
}
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 ' ')
}
}
fn -c2map [col]{
if (not-eq (kind-of $col) list) {
put []
return
}
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
}
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-10-13 18:49:48 +00:00
set lines = [ (eawk [_ @args]{ put $args } $lst) ]
}
each [l]{
2021-08-27 20:06:49 +00:00
var cl = (count $l)
if (> $cl $cc) {
2021-10-13 18:49:48 +00:00
set col = [ $@col (range (- $cl $cc) | each [_]{ put [&align=left &min=0] }) ]
set cc = $cl
}
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
}
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
}
fn -formatline [col line]{
list:loop [i v]{
-format $col[$i] $v
} $line | str:join ''
}
fn format [&col=[] &split=$false @lst]{
2021-08-27 20:06:49 +00:00
var lines = (list:-p $@lst)
if $split {
2021-10-13 18:49:48 +00:00
set lines = [ (eawk [l @args]{ put $args } $lines) ]
}
2021-10-13 18:49:48 +00:00
set col = (-parsecols $col $lines)
each [l]{ -formatline $col $l } $lines
}