From e6bcf19c304681dd48859cd7ce62b87f95070df0 Mon Sep 17 00:00:00 2001 From: Ingo Karkat Date: Mon, 23 Jan 2017 00:00:00 +0100 Subject: [PATCH] file creation --- autoload/ingo/format.vim | 60 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 autoload/ingo/format.vim diff --git a/autoload/ingo/format.vim b/autoload/ingo/format.vim new file mode 100644 index 0000000..2103d5b --- /dev/null +++ b/autoload/ingo/format.vim @@ -0,0 +1,60 @@ +" ingo/format.vim: Functions for printf()-like formatting of data. +" +" DEPENDENCIES: +" +" Copyright: (C) 2013-2017 Ingo Karkat +" The VIM LICENSE applies to this script; see ':help copyright'. +" +" Maintainer: Ingo Karkat +" +" REVISION DATE REMARKS +" 1.029.002 23-Jan-2017 FIX: ingo#format#Format(): An invalid %0$ +" references the last passed argument instead of +" yielding the empty string (as [argument-index$] +" is 1-based). Add bounds check to avoid that +" get() references index of -1. +" 1.015.001 18-Nov-2013 file creation + +function! ingo#format#Format( fmt, ... ) +"****************************************************************************** +"* PURPOSE: +" Return a String with a:fmt, where "%" items are replaced by the formatted +" form of their respective arguments. Like |printf()|, but like Java's +" String.format(), additionally supports explicit positioning with (1-based) +" %[argument-index$], e.g. "The %2$s is %1$d". +"* ASSUMPTIONS / PRECONDITIONS: +" None. +"* EFFECTS / POSTCONDITIONS: +" None. +"* INPUTS: +" a:fmt printf()-like format string. +" % [argument-index$] [flags] [field-width] [.precision] type +" a:args Arguments referenced by the format specifiers in the format string. +" If there are more arguments than format specifiers, the extra +" arguments are ignored (unlike printf()!). The number of arguments is +" variable and may be zero. +"* RETURN VALUES: +" Formatted string. +"****************************************************************************** + let l:args = [] + let s:consumedOriginalArgIdx = -1 + let l:printfFormat = substitute(a:fmt, '%\%(\(\d\+\)\$\|.\)', '\=s:ProcessFormat(a:000, l:args, submatch(1))', 'g') + return call('printf', [l:printfFormat] + l:args) +endfunction +function! s:ProcessFormat( originalArgs, args, argCnt ) + if empty(a:argCnt) + " Consume an original argument, or supply an empty arg. + " Note: This will fail for %f with "E807: Expected Float argument for + " printf()". + let s:consumedOriginalArgIdx += 1 + call add(a:args, get(a:originalArgs, s:consumedOriginalArgIdx, '')) + return submatch(0) + else + " Copy the indexed argument. + let l:indexedArg = (a:argCnt > 0 ? get(a:originalArgs, (a:argCnt - 1), '') : '') + call add(a:args, l:indexedArg) + return '%' + endif +endfunction + +" vim: set ts=8 sts=4 sw=4 noexpandtab ff=unix fdm=syntax :