Q:

How to run a custom command on visually selected text

In my .vimrc I have the following command declared:
:command EscapeUnderscore %s/_/\\_/g

However, I want to be able to visually select a few lines and have the command only affect the selected lines. Currently I get the error E481: No range allowed. I've tried changing %s to just s, but this did not produce the desired result.

A:

Use -range and <line1>/<line2> with your command. Looks like this:
:command -range EscapeUnderscore <line1>,<line2>s/_/\\_/g

See the following for more help:
:h :command
:h :command-range
:h <line1>

