< Rebol Programming
USAGE:
REWORD source values /escape char /into output
Example:
>> reword "$1 is $2." [1 "This" 2 "that"] == "This is that."
DESCRIPTION:
Substitutes values into a template string, returning a new string.
REWORD is a function value.
ARGUMENTS
- source -- Template series (or string with escape sequences) (Type: any-string)
- values -- Pairs of values and replacements (will be called if functions) (Type: map object block)
REFINEMENTS
- /escape -- Choose your own escape char (no escape for block templates)
- char -- Use this escape char (default $) (Type: char any-string)
- /into -- Insert into a buffer instead (returns position after insert)
- output -- The buffer series (modified) (Type: any-string)
SOURCE CODE
reword: make function! [[
{Substitutes values into a template string, returning a new string.}
source [any-string!] "Template series (or string with escape sequences)"
values [map! object! block!] {Pairs of values and replacements (will be called if functions)}
/escape {Choose your own escape char (no escape for block templates)}
char [char! any-string!] "Use this escape char (default $)"
/into {Insert into a buffer instead (returns position after insert)}
output [any-string!] "The buffer series (modified)"
/local vals word a b c d
] [
output: any [output make source length? source]
vals: make map! length? values
foreach [w v] values [
unless string? :w [w: to string! :w]
unless empty? w [poke vals w unless unset? :v [:v]]
]
word: make block! 2 * length? vals
foreach w vals [word: reduce/into [w '|] word]
word: head remove back word
escape: [c: word d: (
output: insert insert/part output a b vals/(copy/part c d) :b
) a:]
char: to string! any [char "$"]
either empty? char [
parse/all source [
a: any [b: [escape | skip]]
to end (output: insert output a)
]
] [
parse/all source [
a: any [to char b: char [escape | none]]
to end (output: insert output a)
]
]
either into [output] [head output]
]]
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.