In vim, how do I make a custom word boundary motion?
Asked Answered
T

2

7

As I understand, w recognizes word boundaries by splitting text into 3 groups:

1) characters that are specified in the iskeyword setting (alphabetic, digits, and underscore)

2) other non-printable characters (symbols)

3) whitespace characters

Each time you press w it goes to the next group 1 or group 2. I'd like to customize it so it only goes to the next group 1, jumping over "symbol words".

What almost works is this:

nnoremap w /\k\+<CR>

which uses the iskeyword character class \k. But it is ugly because it simulates me performing a search, which changes my highlighting, clutters my search history, and who knows what else. Is there way to make this work "cleanly" like the w command normally is?

Talley answered 2/3, 2012 at 21:47 Comment(2)
I don't quite follow what you want. Does W help? It has two groups of characters: whitespace, and non-whitespace, so it always goes to the first character after the next whitespace.Electrocautery
No, it doesn't quite work: W lumps the symbol characters together with alphabetic characters. What I want is to, effectively, lump symbols with whitespace, so that symbols are skipped while still creating word boundaries.Talley
Z
3

I think you are looking for operator pending mode, a.k.a xmap, smap and family.

I have done some examples of these in other answers on SO:

The most relevant example might be

You will also find some techniques that are similar and might be useful for you

Zipah answered 2/3, 2012 at 22:7 Comment(6)
I remember that one. Great answer.Redaredact
Making it a proper motion for operators is great, and that SO answer taught me some new things. But what is really making me unhappy is simulating "me performing a search" to move around, and I would have to do that to define my corresponding xmap and omap.Talley
@Nuno: For the record, the docs say that searching from inside a vimscript (function) will not influence your 'current' search pattern, search history etc. (Anyways, any other side effects could simply be restored in that same function)Zipah
How do I define a function which moves the cursor to the next /\k\+ search result?Talley
This, :search('\m\k\+', 'W'), will move the cursor to the next /\k\+ search results. As a bonus it will not mess up your search history or highlighting. See :h search() for more options.Kirakiran
@PeterRincker Thanks! If you post this as an answer I'll accept it.Talley
M
1

I may not be much help here .. I don't even know what \k means in this context, but you can solve the two immediate problems you present:

nnoremap w /\k\+<CR>:nohl<CR>:call histdel("search", -1)<CR>

It's ugly and the highlighting may flicker, but maybe this will point you in the right direction.

Militate answered 2/3, 2012 at 22:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.