DEV Community

loading...

Convert snake_case to CamelCase in Vim

acro5piano profile image Kay Gosho ・1 min read

This is a small snippet.

Create this function in your shell:

# .bashrc / .zshrc

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

If you use fish:

# .config/fish/config.fish

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

Then, you can convert standard input to CamelCase:

~> echo array_map | camelcase
ArrayMap

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

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

Discussion

pic
Editor guide
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 Author

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

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

Collapse
acro5piano profile image
Kay Gosho Author

Thank you, I didn't know that command!

Collapse
andy profile image
Collapse
acro5piano profile image
Kay Gosho Author

Thank you for sharing my post!

Collapse
maestromac profile image
Mac Siri

This is really cool! Thank you for sharing!

Collapse
acro5piano profile image