Martin Drlík
Martin Drlík

Reputation: 1454

How to move through words in camel-cased identifiers in 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?

Upvotes: 19

Views: 7379

Answers (4)

ergosys
ergosys

Reputation: 49019

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.

Upvotes: 5

ib.
ib.

Reputation: 28954

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>

Upvotes: 24

kikuchiyo
kikuchiyo

Reputation: 3421

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

Upvotes: 3

Hettomei
Hettomei

Reputation: 2233

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.

Upvotes: 4

Related Questions