How do I map a key to run an external command using a visually
selected text? You can the “:vmap” command to map a key in the visual mode. In the mapped command sequence, you have to first yank the text. The yanked text is available in the ‘”’ register. Now, you can use the contents of this register to run the external command. For example, to run the external command “perldoc” on a visually selected text, you can use the following mapping:
:vmap y:!exec "!perldoc '" . @" . "'"
If you want the mapping to work in the visual mode, but not with the highlighted text, you can use the following command:
The above mapping will use the word under the cursor instead of the highlighted text. Note the use of the <C-U> before invoking the “perldoc” external command. The <C-U> is used to erase the range of text selected in the visual mode and displayed on the command line. If the visual range is not removed using <C-U>, then the output from the external command will replace the visually selected text.