3

I want a function to change underline word to little camel for one line.

When I use <shift+v>:s/_\(\w\)/\u\1/g, it work fine.

And then I want to make a function to simplify it, <shift+v>:ToLittleCamel

" underline to little camel
:command ToLittleCamel call ToLittleCamel()
function! ToLittleCamel()
    s/_\(\w\)/\u\1/g
endfunction

but it doesn't work.

1

1 Answer 1

5

If you want to use a :command, I would suggest defining it with -range and passing along the line numbers:

:command -range ToLittleCamel <line1>,<line2>call ToLittleCamel()

This works because when :call has a range and its function is not range, it execute the function once on every line of the range.

You can also make the function range (but keep the call the same above):

function ToLittleCamel() range
  execute a:firstline ',' a:lastline 'substitute /_\(\w\)/\u\1/g'
endfunction

References:

  • :help :command-range
  • :help :command-repl
  • :help <line1>
  • :help :call
  • :help function-range-example
  • :help :func-range
4
  • 1
    It would be nice if your answer also addressed how to adapt the ToLittleCamel() function to turn it into a range function. It's possible to get that from the docs, but it would be nice to include it in the answer, for this simple example.
    – filbranden
    Apr 15, 2022 at 18:16
  • 2
    @filbranden tried from mobile; hope it’s correct :)
    – D. Ben Knoble
    Apr 15, 2022 at 21:59
  • fix: Second arg in example func shoud be a:lastline. It could be a clerical error. (edits must be at least 6 char)
    – Sangria
    Apr 18, 2022 at 9:59
  • @Sangria thanks for calling that out; fixed
    – D. Ben Knoble
    Apr 19, 2022 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.