Pergunta

I want to use :substitute(...) in a case sensitive manner in vim, but fail to do so.

Here's the variable I want to operate on:

let s:Var = 'foo BAR baz'

I can of course explicitely set noic so that in the following lines BAR (of s:Var) is not substituted:

set noic
let s:S1 = substitute(s:Var, 'bar', '___', '')
" print    foo BAR baz
echo s:S1 

Conversly, if ic is set, BAR will of course be substituted:

set ic 
let s:S2 = substitute(s:Var, 'bar', '___', '')
" print    foo ___ baz
echo s:S2

Now, I thought I can use the I flag for :substitute in order to make it case senstitive, but this doesn't seem to be the case:

let s:S3 = substitute(s:Var, 'bar', '___', 'I')
" print   foo ___ baz
" instead of the expected foo BAR baz
echo s:S3

The help for the I flag reads:

[I] Don't ignore case for the pattern.  The 'ignorecase' and 'smartcase'
    options are not used.
    {not in Vi}

My understanding of these lines is that with that flag, BAR should not be substituted.

Foi útil?

Solução

The help message about [I] you quoted is not for substitute() function. it is for :s command.

The flag of substitute() function could have either "g" or "". if you want to do case sensitive match with this function, add \C in your pattern, like:

substitute(s:Var, '\Cbar', '___', '')

check this help text:

The result is a String, which is a copy of {expr}, in which
        the first match of {pat} is replaced with {sub}.
        When {flags} is "g", all matches of {pat} in {expr} are
        replaced.  Otherwise {flags} should be "".

        This works like the ":substitute" command (without any flags).
        But the matching with {pat} is always done like the 'magic'
        option is set and 'cpoptions' is empty (to make scripts
        portable).  'ignorecase' is still relevant, use |/\c| or |/\C|
        if you want to ignore or match case and ignore 'ignorecase'.
        'smartcase' is not used.  See |string-match| for how {pat} is
        used.

Outras dicas

The help for the substitute command says:

When {flags} is "g", all matches of {pat} in {expr} are replaced. Otherwise {flags} should be "".

So the only valid values for {flags} in this instance are "g" or "".

However, using the \C flag directly in the search pattern may work.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top