vim script のリストをフォーマットを指定して出力

ふと、思い立って書いてみた。

[ソース]

function! s:pop_back(list)
    return a:list[ : len(a:list)-2 ]
endfunction

function! s:back(list)
    return remove(a:list, -1)
endfunction

function! s:eval_indent_format(format, indent_space, value)
    let result = substitute(a:format, "%i", a:indent_space, "g")
"    let result = substitute(result, "%s", a:value, "g")
    let result = printf(result, a:value)
    return result
endfunction

function! s:list_format(open, delimiter, close, ...)
    let self = {}
    let self.open = a:open
    let self.delimiter = a:delimiter
    let self.close = a:close
    let self.end = a:0 >= 1 ? a:1 : "%s"
    let self.indent_space = a:0 >= 2 ? a:2 : "  "
    return self
endfunction

function! s:default_list_format()
    return s:list_format("[", "%s, ", "]")
endfunction

function! s:to_output_list(list, ...)
    let list = deepcopy(a:list)
    let format = a:0 >= 1 ? a:1 : s:default_list_format()
    return format.open.
        \join(map(s:pop_back(list),
            \"s:eval_indent_format(
                \format.delimiter, format.indent_space, string(v:val)
            \)"
        \), "").
        \s:eval_indent_format(format.end, format.indent_space, string(s:back(list))).
    \format.close
endfunction


let list = [1, 2, 3]
echo list
echo s:to_output_list(list)
echo s:to_output_list(list, s:list_format("( ", "%s, ", " )"))
echo s:to_output_list(list, s:list_format("{\n", "%i%s\n", "}", "%i%s\n"))
echo s:to_output_list([1, 2, 3], s:list_format("{\n", "%i%s\n", "}", "%i%s\n", "    "))
echo s:to_output_list([1, 2, [3, 4] ], s:list_format("( ", "%s ", " )"))

[出力]

[1, 2, 3]
[1, 2, 3]
( 1, 2, 3 )
{
  1
  2
  3
}
{
    1
    2
    3
}
( 1 2 [3, 4] )

ユーザ側でフォーマットを指定して、リストの出力が出来ます。
インデントスペースの指定もしたかったので、複雑になってしまった…。
あと

[1, 2, [3, 4] ]

みたいなネストしているリストには対応していません。
こっちは別に対応させる予定。
どうでもいいけど、1文を改行する時に \ を付けるのはちょっと手間ですねぇ…。