0

I'm looking to map Ctrl-N to lbvhe in normal mode. This should visually select the word under the cursor, and works fine unless the word is at the beginning of a line.

Having investigated, I've found that – in a mapping – firing h when the cursor is in column 1 (which should simply do nothing) "traps" the cursor at the beginning of the line. Any following movement commands seem to be ignored; j, k, l, e, and w all do nothing.

My mapping works perfectly on any word preceded by whitespace or punctuation, but not words preceded by the previous line's EOL.

1
  • 1
    :h motion.txt will blow your mind.
    – romainl
    Aug 18, 2015 at 5:44

3 Answers 3

7

Use viw to visually select the current word. iw is a text object for the "inner" word.

I suggest you run vimtutor from the command line as well as look at :h quickref for more motions and text objects.

1
  • viw is the sequence I was looking for; thank-you.
    – Blieque
    Aug 18, 2015 at 15:46
2

From :h map-error :

                                                            *map-error* 
Note that when an error is encountered (that causes an error message or beep)  
the rest of the mapping is not executed.  This is Vi-compatible.  

so when you hit h while on the first column (or l on the last one) the mapping fails.


As @peterrincker said you could use viw, which has almost the same effect as your command (if you're not on a word viw will not select anything while your command will select the previous word).


If you still want to use your mapping you could use:

:nnoremap <C-n> :silent! normal! lbvhe^M 

(^M being one character, use <C-v><CR> to enter it).

1
  • 1
    Thanks for the explanation of why the mapping fails. viw is indeed what I was looking for.
    – Blieque
    Aug 18, 2015 at 15:50
2

In addition to @Peter's answer I think you should read :h text-objects because it is a really powerful Vim's feature.

Peter already mentionned iw which selects a word and is pretty close to what you was trying to do. It is worth mentionning aw which allows to select a word + a leading or trailing space (that can be useful to change the place of a word in a sentence without leaving two whitespaces instead of only one).

There is also two other texts objects pretty similar: iW and aW which selects WORDS instead of words (see :h WORD to clarify the difference).

Finally note that text-objects can be used with all the basics commands not only v: diw will delete your word, caW will delete your WORD and a trailing space and switch to insert mode, yaw will yank the word and a trailing space, etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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