Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move through words in camel-cased identifiers in Vim?

Tags:

vim

How to move the cursor before or after the first uppercase letter of a word in Vim?

My motivation is removing or selecting the first word of a camel-case identifier in code. For example, if the cursor is on the m character in the word camelCase, I can use the FcdtC sequence of Normal-mode commands to delete the camel prefix.

Is there a general way to jump to the next occurrence of an uppercase letter in an identifier?

like image 279
Martin Drlík Avatar asked Jan 20 '12 23:01

Martin Drlík


4 Answers

In situations where approaches using only built-in Vim instruments are preferred, the following search commands can be used.

For jumping to the next uppercase character:

/\u

For moving the cursor one character to the right of the next uppercase character:

/\u/s+

or

/\u\zs

If one expects to use a movement like that often, one can always define a key mapping for it as a shorthand, e.g.:

:nnoremap <leader>u /\u/s+<cr>
like image 130
ib. Avatar answered Nov 10 '22 18:11

ib.


I don't think there is anything built-in.

As @ib. indicates, you can use a regular expression motion, but it’s not particularly easy to type. However, there is camelcasemotion plugin that adds the necessary motions, for this, as well as underscore seperated identifiers.

like image 21
ergosys Avatar answered Nov 10 '22 17:11

ergosys


Updated Answer (using @ib.'s contribution)

"select from first char up to First uppercase letter ( after first char )
map ,b bv/[A-Z]<cr>h

Original Answer

Regarding jumping before and after the first uppercase letter—
You can map it if you want to.

"Before next uppercase letter
map ,A /[A-Z]<cr>l

"After next uppercase letter
map ,B /[A-Z]<cr>h

:D. Hope this helps. I'm reading your second question now.

Ok, read it. Now you can do this

bv,A

:D

like image 3
kikuchiyo Avatar answered Nov 10 '22 18:11

kikuchiyo


I think I thought maybe "the vim way" to do it :

Vim allow us to define our own operator !

" movement mapping {
" Delete yank or change until next UpperCase
" o waits for you to enter a movement command : http://learnvimscriptthehardway.stevelosh.com/chapters/15.html
" M is for Maj (as in french)
" :<c-u>execute -> special way to run multiple normal commande in a map : learnvimscriptthehardway.stevelosh.com/chapters/16.html

onoremap M :<c-u>execute "normal! /[A-Z]\r:nohlsearch\r"<cr>

That way giving

DailyAverage.new(FooBarBaz)

If my cursor is on a (from DailyMesure) and I press dM It delete to A and give

Average.new(FooBarBaz)

It works with all command waiting for a movement (c y ........)

This snippet need to be improved because of bad highlight.

like image 2
Hettomei Avatar answered Nov 10 '22 18:11

Hettomei