60

If I have this text in vim, and my cursor is at the first character:

www.foo.com

I know that I can do:

  • cw to change up to the first period, because a word (lowercase w) ends at any punctuation OR white space
  • cW to change the whole address, because a Word (uppercase w) ends only at whitespace

Now, what if I have this:

stupid_method_name

and want to change it to this?

awesome_method_name

Both cw and cW change the whole thing, but I just want to change the fragment before the underscore.

My fallback technique is c/_, meaning 'change until you hit the next underscore in a search,' but for me, that also causes all underscores to be highlighted as search terms, which is slightly annoying.

Is there a specifier like w or W that doesn't include underscores?

82

You can do cf_. f won't highlight the searched character.

You can also do ct_ if you don't want to include the _.

  • 15
    You're confusing f, t, F and T. f moves forward to the character; F moves backward to the character; t moves forward to just before the character; and T moves backward to the character to the right of the target character. So your second example should have been ct_. – garyjohn Feb 10 '11 at 16:55
  • 2
    Now my answer is corrected. Sorry and thank you. – doubleface Feb 10 '11 at 17:12
  • 4
    ct_ is exactly what I wanted. This has now become part of my regular workflow. Thanks! – Nathan Long Mar 2 '11 at 11:59
  • 1
    This is also incredibly extendable and therefore powerful. I'm guessing you can put any character after the f or t and it will go to the next (or prev for caps) occurrence. Thanks. – Dom Nov 9 '17 at 13:16
  • 2
    Vim never fails, only one's understanding of what it is capable of! – Benjamin R Dec 12 '17 at 4:57
64

Put this in your .vimrc:

set iskeyword-=_

Then _ will be treated as a word boundary (though not a WORD boundary), and cw could be used to just change "awesome", and cW to change the whole thing.

See:

:help iskeyword

and

:help word

for more info.

  • 6
    It's great to know that I can define my own word boundaries, but after some thought, I think the best solution is ct_ as doubleface says below, since it's concise and is default vim behavior. – Nathan Long Mar 2 '11 at 12:01
  • This is my personal favorite – Jay Feb 26 '16 at 19:17
  • 2
    I like this one, but it breaks my syntax color coding in php. – Aaron Surrain Mar 16 '17 at 18:05
  • How can I unset or toggle this? – Behe Sep 5 at 9:05
1

camelcasemotion is a pretty handy vim plugin that allows you to move through words when using underscore or camelcase notation. Using this plugin you can place a comma in front of many of the traditional vim motion commands which will allow you to treat words in underscore or camelcase notation as full words.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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