Rom1
Rom1

Reputation: 3207

vim script: working with the visual selection as well as the word under cursor

I have a small vim script that queries Google to insert links in markdown-formatted text. Currently it only works using the word under cursor, which it retrieves using expand("<cword>") and modifies by executing normal mode commands (norm ciw<new_text>).

How could I modify this script so that it works using the visual selection if it exists?

I need basically three things:

Ideally I would like a clean way to do this.

Any hints?

Cheers

Upvotes: 0

Views: 648

Answers (2)

Luc Hermitte
Luc Hermitte

Reputation: 32986

Your visual selection extraction function is too complex. The usual way to proceed is the following: lh#visual#selection().

BTW, you can build the normal mode mapping with:

vnoremap µ :call <sid>DoStuff()<cr>
nmap µ viwµ

Upvotes: 1

Prince Goulash
Prince Goulash

Reputation: 15735

You can handle this case cleanly using a separate visual-mode mapping (vnoremap rather than nnoremap) that calls the same underlying function.

To extract the text, the markers `< and `> (for the start and end of the previous visual selection) may be useful.

To modify the text, you may be able to use gv from your script (re-select the previous visual selection) and then delete or replace it as you wish.

Hope this helps for now; I'll be able to spend a bit more time on it later.

Upvotes: 3

Related Questions