2

I have a file formatted like this

+---------------------------------+
| Text text text                  |
| Text text text                  |
| Text text text                  |
+---------------------------------+

Within the ASCII box I would like to remap the standard VIM keys, like $, _, ... to ignore the ASCII box during editing.

For example, $ should place the cursor on the last letter of the text and not on the '|'. I can make it with the simple

nnoremap <buffer> $ f\|ge

This works great, but when I try to combine the new $ with other VIM commands, this doesn't work any more. For example, d$ deletes the entire like including the last '|' char.

In my understanding, I have to use onoremap somehow to support motions, and then vnoremap to support visual mode.

My question is:

  • How should I remap $ so that it nicely integrates with all VIM-aspects? (visual mode, motions, objects, ...)
  • 2
    Bad idea, really bad idea. Please don't go that route. Rather, please reconsider whether such high-ceremony formatting is really needed. – Ingo Karkat Dec 9 '16 at 14:15
  • @IngoKarkat Yes, actually you are right. This is just an exercise. So, please, don't judge the task itself. But this is definitely doable with vim, right? – Boris Brodski Dec 9 '16 at 14:26
  • You're going to want to look into onoremap. You are in operator pending mode when, for instance, you press d and vim is waiting for a motion. – Tumbler41 Dec 9 '16 at 15:16
5

If you start with this normal mode mapping:

nnoremap <buffer> $ f\|ge

The visual-mode mapping is identical:

vnoremap <buffer> $ f\|ge

Then, for operator-pending mode (like after d, y, and so on), you need a different kind of mapping. :help omap-info tells us:

To ignore the starting cursor position and select different text, you can have the omap start Visual mode to select the text to be operated upon.

Apparently, you need to use :normal to trigger the selection:

onoremap <buffer> $ :<C-u>normal! vf\|ge<CR>

However, we could avoid the duplication of the motion, and delegate to the already defined visual mode mapping (note how :normal! changed to :normal to invoke mappings):

onoremap <buffer> $ :<C-u>normal v$<CR>

Caveat

To implement this consistently for all built-in motions will be quite a challenge. I would not recommend to actually use something like that. Best to get rid of such high-ceremony formatting. If that's not possible, I'd rather temporarily copy the text into a scratch buffer, do the modifications (without borders) there, and then paste back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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