How to convert C style to C ++ style in vim

I got part of the old code and first want to change

(int)a + b; 

in

 static_cast<int>(a) + b; 

There are a lot of them, and there are a lot of them to do manually. Is there a way to use vim to make this happen?

I tried something like

 :%s/\(int\).* /static_cast<int>(\2)/g 

but that will not work. Please advice.

+8
c ++ vim
source share
3 answers

Try the following:

 :%s/(\(.*\))\([^ ]*\)/static_cast<\1>(\2)/g 

This regex, according to your question, assumes there will be a space after the variable name:

Example:
For the following test data:

 (int)a + b (float)x * y (int)z+m 

the result will be

 static_cast<int>(a) + b static_cast<float>(x) * y static_cast<int>(z+m) 

Regular expression explanation

(\(.*\)) - Match everything inside () and write it down
\([^ ]*\) - followed by everything that is not space and captures it

+6
source share

You can use this:

 %s/(int)\(a\)/static_cast<int>(\1)/g 

It is assumed that the variable name is always equal to a . If this is not the case, you can replace a with [az] .

0
source share

I have several mappings for this task in lh-cpp .

In this case, it will be ,,sc , or ,,rc , or ,,dc . (here , actually my <localleader> ).

It is actually implemented as:

 function! s:ConvertToCPPCast(cast_type) " Extract text to convert let save_a = @a normal! gv"ay " Strip the possible brackets around the expression let expr = matchstr(@a, '^(.\{-})\zs.*$') let expr = substitute(expr, '^(\(.*\))$', '\1', '') " " Build the C++-casting from the C casting let new_cast = substitute(@a, '(\(.\{-}\)).*', \ a:cast_type.'<\1>('.escape(expr, '\&').')', '') " Do the replacement exe "normal! gvs".new_cast."\<esc>" let @a = save_a endfunction vnoremap <buffer> <LocalLeader><LocalLeader>dc \ <c-\><cn>:'<,'>call <sid>ConvertToCPPCast('dynamic_cast')<cr> nmap <buffer> <LocalLeader><LocalLeader>dc viw<LocalLeader><LocalLeader>dc ... 
0
source share

All Articles