Tutorial :How do I capitalize the first letter of a word in Vim?



Question:

For a long time I've known that I can use ~ in Vim to toggle the case of a character. But is there a way to map a key to capitalize a word and go back to the previous position?

For example:

I like to drink Coca co[l]  

If my cursor is at "l" and I realize I need to make the "c" capitalize as well, currently, I need to do:

<C-c> b ~ ll i  

Is there a way to map a single key to make the first letter of the word under cursor to be capitalized and keep the cursor at original position?


Solution:1

:nmap <whatever> m`b~``  


Solution:2

Personally, this is exactly the kind of thing I prefer not to make a macro for. There's no need to fill up your .vimrc with dozens of such one-off solutions, because the solution flows so naturally from the "toolbox" of standard Vim commands, that you can just string it together like second nature.

I'm typing a long word:

the gallicizatio|  

(the | is the position of the cursor). Suddenly I realize that I forgot to capitalize the G of "Gallicization". So, bam!, I hit ESC (which is mapped to the caps lock key on my keyboard, so it takes only a flick of the pinky), followed by b~A, and I continue typing as if nothing happened. That errant g was capitalized in the time it would take an Emacs user to begin moving his right hand toward the arrow keys, and I've already moved on to the rest of the sentence.

In contrast, with a macro that I haven't used in a while, it would probably take me more time just to remember what key(s) I assigned to that macro. The better solution is to learn the important "core" commands very well, which can be combined on the fly according to simple rules, with millions of possible effects.


Solution:3

you can also use macro

q<register> <C-c> b ~ ll i q  

and then do @<register> every time you need to use it.


Solution:4

I find myself doing this often, and using the EX command line to got through multiple records that match a condition. In this case, I use a backreference that looks like this:

:%s/\(\w\)\(\w*\)/\U\1\L\2/g

and BOOM, problem solved across all the words that are in a certain context.

EDIT: Look here too, just realized there was this link which has similar answers:

Capitalize first letter of each word in a selection using vim


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »