简体   繁体   中英

Vim, swapping words with accented characters

I'm trying to use the following mappings to swap words in Vim:

" Swap current word with previous one (push word to the left)
nnoremap <silent> <A-h> "_yiw?\k\+\_W\+\%#<CR>:s/\(\%#\k\+\)\(\_W\+\)\(\k\+\)/\3\2\1/<CR><c-o><cl>:noh<CR>

" Swap current word with the next one (push word to the right)
nnoremap <silent> <A-l> "_yiw:s/\(\%#\k\+\)\(\_W\+\)\(\k\+\)/\3\2\1/<CR><c-o>/\k\+\_W\+<CR><c-l>:noh<CR>

I also have in my vimrc file the following

set isk=@,48-57,_,192-255,:,#

The above mappings work fine for swapping (pushing words) except when an accented character starts a word. Since I write in Spanish accented characters are used frequently so how can i change the regex to solve this problem?

The problem lies in the \\_W "match non-WORDs and newline" atom. In Vim, WORDs are limited to ASCII-characters, so your accented characters match here and create a wrong boundary. Instead, you want "non-keywords and newline". Since \\K is not the negation of \\k , we have to use \\%(\\k\\@!\\_.\\) "any character (and newline) that is not a keyword". Those are the resulting mappings:

nnoremap <silent> <A-h> "_yiw?\k\+\%(\k\@!\_.\)\+\%#<CR>:s/\(\%#\k\+\)\(\%(\k\@!\_.\)\+\)\(\k\+\)/\3\2\1/<CR><c-o><c-l>:noh<CR>

nnoremap <silent> <A-l> "_yiw:s/\(\%#\k\+\)\(\%(\k\@!\_.\)\+\)\(\k\+\)/\3\2\1/<CR><c-o>/\k\+\%(\k\@!\_.\)\+<CR><c-l>:noh<CR>

i would usually prefer a macro, lets say we have a line like following(yes, it doesn't make any sense i am just using it for explanation):

experimentación implacable

now in vim i would go to start of this line, and press q followed by a record key(any alphanumeric key) let us say 'l'. then record my actions:

  1. Press 'dW' to cut the word, (capital w and assuming that the word ends in a space)

  2. Proceed to end of word with e

  3. Add a space by pressing 'a'

  4. Press ''

  5. Type in 'p' to paste.

I know its too much trouble the first time, but once you've saved it you can recall it on any pair of words by '@l', 'l' is our record key from above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM