I often work on CSS files or other files that require twiddling numbers. I would love the ability to have a key that refers to integers much in the way that w refers to a word, or ( refers to a sentence. For example, in a css file I could navigate to the beginning of a height declaration, and change it's value without having to retype "px" a the end, which is what happens if I use w.
Is there such a thing, but I'm missing it in the documentation, or is there a way to add this functionality to my .vimrc?
Bonus points if there were a way to use it like ci" where I could be at the begining of the line and use the "change internal" command to jump to AND change the next integer.
More bonus points if I could do simple arithmetic. I would love to be able to issue a concise command that was short for "Add too, internal, integer, 5" and have the next integer on the current line be five grater then it was when I started.
Edit:
Some really great proposals everyone, some great ideas that are sure to improve my work. Thanks! Hassek's answer is probably the most likely to end up in my work-flow, but none of the others seem to have (fully) answered my inital question: A motion that works on integers. The proposal tracked down by romainl appears to have that goal, but I can't get it to work reliably.
For myself (and others perhaps) I will clarify my wants below:
A key that acts much in the way w acts for words, but on integers so that I can simply add it to my mental vim vocabulary and use it seamlessly. This includes the following scenarios. (I will use d as my example key):
Normal mode d: Jump to the next integer
Normal mode cd: Change to the end of the integer under the cursor (Note that cw is a special case that SHOULD change to the NEXT word. cw actually acts like ce.) I would expect this special case to be implemented with integers as well
Visual mode id: Select [count] integers.
Visual mode ad: Select [count] integers. Leading or trailing white space is included.
Am I missing any behavior that w has that might be expected for a new motion? Is there even a key available in both normal and visual modes?
you can add or substract from integers using this commands:
<num>Ctrl-a (to add)
<num>Ctrl-x (to substract)
and it will go right to the next number in line and execute the command
See this proposal. It looks good.
edit
Indeed that one is quite nice. This made me think that my habit of doing /<number><Esc> was not very efficient so I've added these mappings (and slightly modified the mappings above for consistency) to my ~/.vimrc. Let's see if they are useful in the long run:
nnoremap è /\v\d+<CR>
nnoremap é ?\v\d+<CR>
At first sight, èciè132<Esc> seems to be marginally better than /2<Esc>{count}s132<Esc> in terms of keypresses but substantially better if it allows me to skip a. checking the first digit of the value I want to change and b. counting the characters to replace.
Time will tell.
re-edit
Here are the function and its mappings:
onoremap N :<c-u>call <SID>NumberTextObject(0)<cr>
xnoremap N :<c-u>call <SID>NumberTextObject(0)<cr>
onoremap aN :<c-u>call <SID>NumberTextObject(1)<cr>
xnoremap aN :<c-u>call <SID>NumberTextObject(1)<cr>
onoremap iN :<c-u>call <SID>NumberTextObject(1)<cr>
xnoremap iN :<c-u>call <SID>NumberTextObject(1)<cr>
function! s:NumberTextObject(whole)
normal! v
while getline('.')[col('.')] =~# '\v[0-9]'
normal! l
endwhile
if a:whole
normal! o
while col('.') > 1 && getline('.')[col('.') - 2] =~# '\v[0-9]'
normal! h
endwhile
endif
endfunction
With this, I can:
vcdy part of a number from the cursor until its end with <command>N. Somehow similarly to <command>e or <command>w.
Here are some random numbers: 24 7635 1000018
^--->
It doesn't work if the cursor is not already on the number and it doesn't go backward.
vcdy a whole number with <command>iN.
Here are some random numbers: 24 7635 1000018
<-^--->
Again, it doesn't work if the cursor is not already on the number.
The whole thing could be improved, sure, but that's a start!
endedit
I work a lot with CSS, too.
I use two strategies to change numerical values:
{count}<C-a> and {count}<C-x>, as in Hassek's answer, when I know by how much I want to increment/decrement the number. Say I want to turn 20px into 25px, a simple 5<C-a> does the trick without requiring me to move the cursor to the number. This is extremely cool.
/<number><CR>{count}s<new number> when the new value is very different from the current value and I feel to lazy to calculate the delta. /2<CR>2s67<Esc> would allow me to change 23px into 67px. /2<CR>R67<Esc> is another way but it's only good if the new value as the same length as the current value. Use f<number> if you are on the same line.
Note that you can insert the result of expressions with <C-r>=137-42<CR> which I use it very often as well.
I found something in the depths of the internetz here and modified it like this
nnoremap ,n /\v\d+/b<cr>mah/\v\d+/e<cr>mb`av`b
vnoremap ,n <esc>/\v\d+/b<cr>mah/\v\d+/e<cr>mb`av`b
\v\d+ searches for a group of digits
/b + mah goes to its beginning, sets a mark and goes one character back so we can again
\v\d+ search for the same group of digits
/e + mb goes to its end and sets another mark and at last
`av`b visually selects from the first to the second mark
Related
Given a vim document with multiple occurrences of a specific placeholder, say <%%>, I want to be able to jump to the next placeholder from the beginning of the document: More explicitly, if the document is given by
$\frac{<%%>}{<%%>}$
I want to press a key such that the first placeholder gets removed, i.e. we have
$\frac{}{<%%>}$
where the cursor is at the position of the placeholder and vim is in insert mode.
I'm aware of the vim-latex plugin which implements such a behaviour but only need this one feature. I tried to use the /-search of vim but didnt get the cursor position right.
Thanks in advance for any advice.
lh-brackets provides this feature -- actually vim-latex placeholder system has been inspired by lh-brackets one.
The idea to implement this feature, is:
to look for the pattern of the placeholder -- prefer search() to know whether something has been found: no selection shall be done otherwise
Actually doing it correctly may require a couple of calls to searchpair() to handle the case where the cursor is in the middle of the placeholder, see lh-brackets code as search(..., 'c') is not enough;
select this pattern -- v + movement 3<right> for instance
and finally either go into SELECT-mode (gh <c-g>) or remove the placeholder and go into insert mode (s)
If your placeholder pattern is exactly <%%>, it'll be quite simple to implement.
" I factorize common code without introducing the exact keybinding
" NB: we have to use the ancestor of map-<expr> as the later doesn't
" permit to move the cursor -> we execute the expression register: :h #=
" NB: As said earlier a correct implementation would require to call searchpair()
" twice in case the cursor is within a placeholder, see lh-brackets code
nnoremap <silent> <Plug>(jump-next) #=(search('<%%>') > 0 ? "v3l<c-g>" : '')<cr>
vmap <silent> <Plug>(jump-next) <c-\><c-n><Plug>(jump-next)
imap <silent> <Plug>(jump-next) <c-\><c-n><Plug>(jump-next)
" Tests shall be done in a real plugin before binding to the chosen shortcut: µ, <f3>, <c-j>, <tab>...
nmap <silent> µ <Plug>(jump-next)
vmap <silent> µ <Plug>(jump-next)
imap <silent> µ <Plug>(jump-next)
If sometimes it could become <%somestring%>, then I would definitively recommend using lh-brackets or any snippet engine that already takes care of this -- for instance, mu-template would permit to use your exact snippets/templates by changing locally the default placeholder characters with VimL: let s:marker_open = '<%' +
VimL: let s:marker_close = '%>' (I'm also maintaining mu-template which depends on lh-brackets).
NB: lh-brackets also provides surrounding (non intrusive), and bracket pairs insertion (can be deactivated: add :let g:cb_no_default_brackets = 1 in your .vimrc)
Using a macro might help.
In your example, use /<%%> to search for your placeholder. Then gg will take you at the beginning of the document.
Then start the macro with qa for instance. Go to the next occurrence of your placeholder with n. Then, ca< will remove the placeholder. C-o q will stop recording, while keeping you in insertion mode.
To go to and replace the next placeholder, just do #a (execute the macro stored in register a)
Does this mapping help?
:nmap %% /<%%><cr>ni
It executes a search (/<%%><cr>), repeats the search with n to skip the 1st placeholder and goes to the second. Then it switches (i) to Insert Mode.
The idiom for swapping two characters in Vim is xp.
See the help at :h 04.5, final paragraph, and Vim: how do I swap two characters?.
But very occasionally I need to do two or more swap operations in a row. I'm often surprised that what feels like a single operation to me, xp, is actually two operations to Vim. This makes it impossible to repeat xp with .. (Or atomic undo with u.)
Is there a way to swap two characters in a single operation that I can quickly repeat with .?
This isn't ideal, but if you store xp as a macro, it will be repeatable after you've executed the macro. So instead of xp, you're using, say #s (for swap). Then ## will repeat it. Not as nice as ., but it does work.
Edit: You know, I'm sure there's a way to accomplish this with some vimscript and tpope's repeat.vim. Sadly, my vimscript is not up to snuff. I got this far - maybe someone can correct where I'm going wrong?
fun! DoSwap()
:normal xp
silent! call repeat#set("\<Plug>Swap",1)
endfun
nnoremap <silent> <Plug>Swap :call DoSwap()<CR>
nmap <Leader>s <Plug>Swap
The problem with this is that once you enter \s, it does indeed swap the characters you're on, and it DOES repeat when you hit ., but it jumps to the beginning of the line first, which is not what you want. But I do think this can be done, I'm just not all the way there.
Here's an idea. Suppose the cursor is on the "y" of the word "oyxgen".
In normal mode, type
2sxy<Esc>
Now the word reads "oxygen". Find the next instance of the typo (fy) and repeat the change (.).
Too bad this works only for the specific swap "yx" to "xy", so this isn't the definitive solution.
Vimcasts.org has published an episode that addresses this very problem.
As #Jeremy guessed the solution is to use the repeat.vim plugin. Then simply add the following <Plug> mapping and key mapping to your vimrc.
nnoremap <silent> <Plug>Transpose xp:call repeat#set("\<Plug>Transpose")<CR>
nmap cp <Plug>Transpose
The mapping shown here uses cp. cp is the new xp, repeatable with . but otherwise exactly the same.
Now all that remains is getting used to it.
Since I frequently don't use the excellent motions and text objects that vim provides, (and since "Holding down 'j' is a vim anti-pattern,") I'd like vim to assist me in training to use these instead of using hjkl more than a few times in a row.
When I started using vim, I was annoyed that I didn't use hjkl to move but would instead use the arrow keys. As a reminder not to do this, I remapped the arrow keys to keep myself from using them - I knew using the home row to navigate would be a better long term plan, so I cut out the positive reinforcement I would get by having working arrow keys.
map <left> <nop>
map <right> <nop>
# I quickly removed nop's for up and down because using
# the mouse wheel to scroll is sometimes useful
I no longer need these mappings in my .vimrc because this worked very well, and I quickly switched, without having to make a conscious effort to do so. In a similar fashion, I'd now like to cut off my repeated use of basic movement keys hjkl as well. I was envisioning something like this:
let g:last_mov_key = 'none'
let g:times_mov_key_repeated = 0
function! MovementKey(key)
if (g:last_mov_key == a:key)
let g:times_mov_key_repeated = g:times_mov_key_repeated + 1
else
let g:last_mov_key = a:key
let g:times_mov_key_repeated = 0
endif
if g:times_mov_key_repeated > 3
echo "Negative Reinforcement!"
endif
endfunction
noremap j :call MovementKey('j')<CR>gj
noremap k :call MovementKey('k')<CR>gk
noremap h :call MovementKey('h')<CR>h
noremap l :call MovementKey('l')<CR>l
But this breaks in visual mode, and I imagine in tons of other cases where using the vim command line in the middle of something changes the state when it shouldn't. How can I constrain myself to have to use more complicated motions?
Edit: Question edited after first two answers for clarity, paragraphs reordered. I want some assistance from vim moving beyond romainl's "level 0". So far answers advise me not to waste my time, but what if we assume that I'm a fan of the learning technique where I change my habits by altering my environment to change incentives? In this model I want to accomplish a task, say, scrolling down a page, and I will more or less randomly attempt key combinations until I achieve that task. Dopamine signalling etc. in my brain will reinforce the action which eventually achieves this result. I could focus on remembering not to use hjkl, or I could focus on the task I was originally trying to do anyway, edit text, and without really thinking about it find myself using more efficient editing techniques.
You listen to other people waaay too much. Just use for movement whatever keys you like best, and leave other keys alone. Remapping hjkl keys is somewhat troublesome, and best not done, because they're hardcoded in vim due to historical reasons.
One thing I've found that works is :noremap jj <nop>. Vim will delay the j motion because it thinks you might be extending it, which slows you down enough to try something else. You also can't hold the j key down anymore because it just triggers the nop instead. You can still use the button in emergencies, but it's frustrating enough to make you avoid it in the day-to-day editing.
EDIT
After reading your edit and your comment here is the radical solution I propose: remap hjkl to do super annoying things:
nnoremap h $
nnoremap l 0
nnoremap j gg
nnoremap k G
" and so on for other modes
hjkl are mapped to the extreme opposite of their original behaviour, essentially making them completely unusable. You should do the same for their synonyms (:h h, :h j, :h k, :h l) too for completeness but there are cases when character-by-character/line-by-line movement is useful. In such cases you will be glad to have + or - or <Space>.
I don't really like that kind of pavlovian method, though. I find it too brutal and the risk that you actually get used to these weird mappings seems quite high.
END EDIT
Short version:
Neither the arrow keys nor hjkl are worth using so your remappings are ultimately useless. After a while you will get used to Vim's motions and text-objects. Use what feels more natural to you in the meantime. Don't rush it. It will come. Naturally.
Long version:
Are you a touch typist? Or do you plan to learn touch typing?
I'm not a touch typist and I don't plan to ever become one: I use hjkl only to actually input hjkl in INSERT mode.
When I need to move 1 or 2 lines above or below without a particular "target" I use the arrow keys, when I need to move a couple letters to the left or to the right I use the arrow keys. There is no shame in doing that.
There is a problem, however, when you type jjjjjjjjjj or hit the down arrow key 10 times to move down 10 lines: jjjjjjjjjjj is obviously just as bad as ↓↓↓↓↓↓↓↓↓↓
This stupid mantra of "don't use the arrow keys" is just the tree that hides the forest: it's repeated so often that it makes you focus on useless patterns/antipatterns instead of actually learning more powerful ways.
I don't want to paraphrase the beautiful Your problem with Vim is that you don't grok vi. but you could see it as "levels of enlightenment":
Level 0 would be
jjjjjjjjjjj or ↓↓↓↓↓↓↓↓↓↓ then all the necessary horizontal movements to reach your target.
Reading the line above, isn't it rather obvious that the hjkl Vs ←↓↑→ debate is absolutely stupid?
Whether you use one method or the other you end up mashing your keyboard moving vertically AND horizontally to reach the value you want to edit. What a waste. And what a waste of time and energy to force yourself to use one method over another since both are equally bad.
Level 1 would be
10j22l to go down 10 lines and reach your target 22 characters to the right. While it's a lot less typing, you now have to count lines and characters which is not particularly better.
Level 2 would be
10jwww to go down 10 lines and reach your target 3 words to the right
or 10jf# to go down 10 lines and jump to the first letter of your target (an hex color value).
Hmm, that's a lot better.
Level 3 would be
/#<CR> to jump directly to your target (an hex color value, as before). If it's above your current position you would do ?#<CR>.
If you are a touch typist, or are training to become one, the debate is settled: hjkl (or jkl; as some like to remap them) are quick and natural and you don't need arrow keys at all and if you are not, the benefits of using hjkl over ←↓↑→ are at best minimal.
Focus on eEbBwWfFtT/?} and Co. instead. One bit at a time. Don't "force" yourself.
I would like to propose a solution that is more in line with the OP's way of thinking.
I too decided that blocking certain motions if not preceded by a count was a good idea, as discussed here. I too tried a simply direct remapping, but this did not work in many contexts, as described by the OP.
But I did finally come up with an approach that worked using key maps that returned an expression:
function! DisableIfNonCounted(move) range
if v:count
return a:move
else
" You can make this do something annoying like:
" echoerr "Count required!"
" sleep 2
return ""
endif
endfunction
function! SetDisablingOfBasicMotionsIfNonCounted(on)
let keys_to_disable = get(g:, "keys_to_disable_if_not_preceded_by_count", ["j", "k", "l", "h", "gj", "gk"])
if a:on
for key in keys_to_disable
execute "noremap <expr> <silent> " . key . " DisableIfNonCounted('" . key . "')"
endfor
let g:keys_to_disable_if_not_preceded_by_count = keys_to_disable
let g:is_non_counted_basic_motions_disabled = 1
else
for key in keys_to_disable
try
execute "unmap " . key
catch /E31:/
endtry
endfor
let g:is_non_counted_basic_motions_disabled = 0
endif
endfunction
function! ToggleDisablingOfBasicMotionsIfNonCounted()
let is_disabled = get(g:, "is_non_counted_basic_motions_disabled", 0)
if is_disabled
call SetDisablingOfBasicMotionsIfNonCounted(0)
else
call SetDisablingOfBasicMotionsIfNonCounted(1)
endif
endfunction
command! ToggleDisablingOfNonCountedBasicMotions :call ToggleDisablingOfBasicMotionsIfNonCounted()
command! DisableNonCountedBasicMotions :call SetDisablingOfBasicMotionsIfNonCounted(1)
command! EnableNonCountedBasicMotions :call SetDisablingOfBasicMotionsIfNonCounted(0)
DisableNonCountedBasicMotions
Note that the code is included here for convenience, but I would check with the gist as well to see if there have been updates/fixes.
You can relax the constraint for horizontal motions, or
add/remove other motions by setting the list of the keys/commands
that are effected, g:keys_to_disable_if_not_preceded_by_count, in your ~/.vimrc.
For example, the following only enforces count-prefixed motions for "j" and "k":
let g:keys_to_disable_if_not_preceded_by_count = ["j", "k"]
Also, as noted in the gist, you might find it really useful to add something like this in your ~/.vimrc as well as the code above:
set number
if has('autocmd')
augroup vimrc_linenumbering
autocmd!
autocmd WinLeave *
\ if &number |
\ set norelativenumber |
\ endif
autocmd BufWinEnter *
\ if &number |
\ set relativenumber |
\ endif
autocmd VimEnter *
\ if &number |
\ set relativenumber |
\ endif
augroup END
Or install a plugin line vim-numbers.
Even though this question has (long) been answered to the OP's satisfaction with an alternate approach, I am adding my solution here in case anyone is searching for something different.
A very platform-specific solution I just found, Mac only: using something vim-like (I've only gotten this to work with PyCharm in vim mode), turn on MacOS key holding*, which makes holding down e bring up èéêëēėę to choose from. This makes holding down keys never work! This is really annoying unless you are trying to learn to stop holding down keys!
If I could figure out how to make this work in my terminal emulator (iTerm, Terminal.app, etc) this could probably be made to work in normal vim?
*This turns this feature on in case it's disabled for you:
defaults write -g ApplePressAndHoldEnabled -bool true
I have word-wrap enabled and tend to have quite long lines.
But moving around inside a line that's actually 4 lines high with "w" is cumbersome. I keep using / to jump to the word I'm looking for, but that seems overdoing it a bit.
Any hints on how to move more quickly inside of a line?
Thanks,
MrB
You can use $, 0, and ^ to move to line endpoints and then use w and b. Also, adding a numeric argument to w and b can accelerate the process, so using 6w instead of just w can put you about to where ou need to be.
Using f and t to move to individual characters will help also. (I use this typically with punctuation. If, for example, I have four sentences on one long line 2f. will go to the end of the second sentence)
Using the ( and ) keys are an alternative way to navigate entire sentences.
Splitting out long lines into multiple lines (manually, or with set tw=72 [or 80]) can make editing them simpler. You can always join them later with J.
Something I just discovered, you can move up and down one displayed line by using gj and gk. That way, you can treat your one wrapped line as multiple lines.
If you comment on the type of data you're editing, it might make it easier for us to make suggestions.
I think you can benefit from gk and gj instead of just k and j.
Also look at 'virtualedit' for some options that allow you to cursor through 'void' areas without flicking the cursor to the next best physical character.
You might want to (temporarily)
nnoremap <buffer> k gk
nnoremap <buffer> j gj
Leave out the <buffer> part to apply this globally.
You can use ( and ) to navigate by sentence; it just looks for ., but that can be immensely helpful, especially if you don't like the sentence and want to change it: (c) will jump to the beginning of the current sentence, then change the entire sentence.
You can also use w and e, with count modifiers, to move words. 3w will move three words at a time.
You can also use f and F to search forward and backwards for a specific character. This is much more useful if you're looking for the word quite or syzygy than the. :)
My preferred strategy while jumping around long lines is to use f F and t T to zero in on the character. What makes this family of motions supercharged is that you can utilize the ; and , motions, so you don't have to count the position of character relative to cursor, but just step through them (extremely useful with
' " . etc)
Let's say we have a line:
reallyLongObjectName.longMethod().prettyPrettyLongMethod().burp();
If we need to jump to, say, the third dot from the beginning of the line, we can use either 3f. or f.;; visiting two dots and landing on third.
While the ; , style can use more keystrokes, I found it more agile and fun overall.
If you choose to go the route of remapping these:
nnoremap k gk
nnoremap j gj
here are a couple others along the same lines:
nnoremap 0 g0
nnoremap $ g$
nnoremap ^ g^
I recently started using a plugin that I find really nice to move very quickly inside a line (or the whole file).
The plugin's name is PreciseJump and you can find it here.
When you use this plugin it defines to mappings _f and _F.
If you type _f followed by x it will highlight all x characters and will replace temporarily with other characters that you can press to jump to that location. Check the script page for an illustration.
You can also move around with W B that will skip to the next space :)
G moves to the end of the document
Please notice that using "g" followed by Up or Down arrows indeed works fine, but if you have long lines and move quickly you may enter "gg" by mistake and end-up at the top of the text...! (Undo will not bring you back, and AFAIK there is not one-key-pressed way to go back to where you were.)
It happened to me too many times.
What I did was, and I suggest you, to modify (or create) your "~/.vimrc" and add these two lines:
map <C-Up> g<Up>
map <C-Down> g<Down>
This will map you control-up and control-down to the movements commands. Will make mistyping "gg" impossible and is perfectly coherent with control-right and control-left to move around long lines.
If you add these other two lines, you can use the same command in insert mode (!)
imap <C-Up> <C-[> g<Up> i
imap <C-Down> <C-[> g<Down> i
(VIM is great !)
Greg Ruo
Emacs has a useful transpose-words command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.
For example, ‘stack |overflow’ + M-t = ‘overflow stack|’ (‘|’ is the cursor position).
<a>|<p> becomes <p><a|>.
Is it possible to emulate it in Vim? I know I can use dwwP, but it doesn’t work well with punctuation.
Update: No, dwwP is really not a solution. Imagine:
SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) )
// with cursor here ^
Emacs’ M-t would have exchanged b and c, resulting in (a)(c)(b).
What works is /\w
yiwNviwpnviwgp. But it spoils "" and "/. Is there a cleaner solution?
Update²:
Solved
:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,<CR>kgJ:nohl<CR>
Imperfect, but works.
Thanks Camflan for bringing the %# item to my attention. Of course, it’s all on the wiki, but I didn’t realize it could solve the problem of exact (Emacs got it completely right) duplication of the transpose-words feature.
These are from my .vimrc and work well for me.
" swap two words
:vnoremap <C-X> <Esc>`.``gvP``P
" Swap word with next word
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> *N*
Depending on the situation, you can use the W or B commands, as in dWwP. The "capital" versions skip to the next/previous space, including punctuation. The f and t commands can help, as well, for specifying the end of the deleted range.
There's also a discussion on the Vim Tips Wiki about various swapping techniques.
In the middle of a line, go to the first letter of the first word, then do
dw wP
At the end of a line (ie the last two words of the line), go to the space between the words and do
2dw bhP
From the handy Equivalence of VIM & Emacs commands
You could add shortcut keys for those by adding something like the following to your vimrc file:
map L dwwP
map M 2dwbhP
In that case, SHIFT-L (in command-mode) would switch words in the middle of the line and SHIFT-M would do it at the end.
NB: This works best with space-separated words and doesn't handle the OP's specific case very well.
There's a tip on http://vim.wikia.com/wiki/VimTip10. But I choose to roll my own.
My snippet has two obvious advantages over the method mentioned in the tip: 1) it works when the cursor isn't in a word. 2) it won't high-light the entire screen.
It works almost like emacs 'transpose-words', except that when transposition is impossible, it does nothing. (emacs 'transpose-words' would blink and change cursor position to the beginning of current word.)
"transpose words (like emacs `transpose-words')
function! TransposeWords()
if search('\w\+\%#\w*\W\+\w\+')
elseif search('\w\+\W\+\%#\W*\w\+')
endif
let l:pos = getpos('.')
exec 'silent! :s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/'
call setpos('.', l:pos)
let l:_ = search('\(\%#\w\+\W\+\)\#<=\w\+')
normal el
endfunction
nmap <silent> <M-right> :call TransposeWords()<CR>
imap <silent> <M-right> <C-O>:call TransposeWords()<CR>
You can use dwwP or dWwP as Mark and CapnNefarious have said, but I have a few notes of my own:
If the cursor is on the first letter of the second word, as in the example you gave, you can use dwbP (or dWbP to handle punctuation);
If the cursor is in the middle of the word, you can use dawbP/daWbP.
There's a transpose-words script on vim.org that works beautifully.