Last active
August 29, 2017 16:39
-
-
Save toomasv/af2014ad97e817e9597e4e4c82b3b873 to your computer and use it in GitHub Desktop.
Formatting a value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Red [ | |
Author: "Gregg Irwin" | |
File: "%fill.red" | |
Source: "Gitter @greggirwin " | |
Reference: ":point_up: [May 4, 2017 6:50 PM](https://gitter.im/red/red/welcome?at=590b4daac93941e153c94b8e)" | |
Changed-by: "Toomas Vooglaid" | |
Changed-date: "2017-05-05" | |
Change: "Added 'justify and helper 'x'" | |
] | |
x: make op! func [n c][pad/with copy "" n to char! c] | |
fill: function [ | |
"Fill part of a template string with a formed value" | |
str [any-string!] "Template string" | |
align [word!] "[left center right justify]" | |
val "(formed) Value to insert in template string" | |
;/trunc "Truncate val if longer than str" ;?? make ellipsis last char if truncated? | |
][ | |
str: copy str ; Don't modify template string | |
if not any-string? val [val: form val] ; Prep the value | |
diff: (length? str) - (length? val) ; Find the length difference between them | |
if not positive? diff [return val] ; Never truncate the formed value | |
pos: switch/default align [ | |
left [1] | |
center [add 1 to integer! divide diff 2] | |
right [add 1 diff] | |
justify [ | |
num: length? split copy val " " ; Number of words | |
unless num < 2 [ ; Unless too few word | |
len: length? replace/all copy val " " "" ; Length without spaces | |
diff2: (length? str) - len ; Difference of template and spaceless string | |
splen: diff2 / (num - 1) ; Length of would-be spaces | |
remains: diff2 % (num - 1) ; Additional spaces to distribute | |
replace/all val " " splen x " ";pad/with copy "" splen #" " ; Replace single spaces to longer ones | |
if 0 <> remains [parse val [remains [thru some " " insert " "]]] ; Distribute additional spaces | |
] | |
1 | |
] | |
][1] | |
either align = 'justify [ ; Some special treatment | |
w: charset [not " "] ; Non-spaces | |
parse val [some [to w s: copy word to [" " | end] (head change at str index? s word)]] ; Transfer words to template | |
str ; Return template | |
][ | |
head change at str pos val | |
] | |
] | |
comment {e.g. | |
template: "+____________+" | |
fill template 'left "" | |
fill template 'left "abc" | |
fill template 'right "abc" | |
fill template 'center "abc" | |
fill template 'justify "ab cd ef" | |
; Long justify | |
sentence: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." | |
fill 150 x "_" 'justify sentence | |
; Hanoi tower | |
lines: ["_" "_|_|_" "_|_____|_" "|_________|"] | |
foreach l lines [print fill " " 'center l] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment