DEV Community

Kay Gosho
Kay Gosho

Posted on

Convert snake_case to CamelCase in Vim

This is a small snippet.

Create this function in your shell:



# .bashrc / .zshrc

camelcase() {
    perl -pe 's#(_|^)(.)#\u$2#g'
}


Enter fullscreen mode Exit fullscreen mode

If you use fish:



# .config/fish/config.fish

function camelcase
    perl -pe 's#(_|^)(.)#\u$2#g'
end


Enter fullscreen mode Exit fullscreen mode

Then, you can convert standard input to CamelCase:



~> echo array_map | camelcase
ArrayMap


Enter fullscreen mode Exit fullscreen mode

These functions are useful themselves. Furthermore, you can use them in Vim.

Select snake_case lines to be converted, then type !camelcase then press return key.

out.gif

Appendix

You can convert CamelCase to snake_case with this function:



function snakecase
    perl -pe 's#([A-Z])#_\L$1#g' | perl -pe 's#^_##'
end


Enter fullscreen mode Exit fullscreen mode

We can enhance vim using command line function.
Hope this article helps you have a better CUI experience in Vim.

Top comments (8)

Collapse
 
5n4p_ profile image
Andreas Schnapp

Nice article and example how powerfull normal shell function calls can be in vim.

If you want a elegant long term solution for allcase types (snake- camel- mixed- dot-cases) then I would recommend to take a look at this plugin from tpope (expecially take a look at the Coercion hotkeys):

github.com/tpope/vim-abolish

Collapse
 
acro5piano profile image
Kay Gosho

Thank you for your comment!
Yes, I wanted to tell that we can easily enhance vim with shell commands.
For me vim script is hard to code, so I wrote this function.

Thank you for sharing nice plugin, too. Coercion looks nice with less type :)

Collapse
 
vpzomtrrfrt profile image
VpzomTrrfrt • Edited

Alternatively:
command -range CamelCase <line1>,<line2>s/\(_\)\(.\)/\u\2/g

Collapse
 
acro5piano profile image
Kay Gosho

Thank you, I didn't know that command!

Collapse
 
andy profile image
Andy Zhao (he/him)
Collapse
 
acro5piano profile image
Kay Gosho

Thank you for sharing my post!

Collapse
 
maestromac profile image
Mac Siri

This is really cool! Thank you for sharing!

Collapse
 
acro5piano profile image
Kay Gosho

Thank you!